Мне интересно, как передать вычисляемую переменную дочернему компоненту (в слоте). Основной компонент восстанавливает массив объектов с помощью запроса post. Что на самом деле радует, так это то, что переменная «Ветви», кажется, заполнена пустым обещанием, которое представляет данные результата. Поэтому я получаю предупреждение, потому что компонент list ожидает, что «Branches» будет массивом. Я попытался отложить рендеринг содержимого слота, используя "v-if =" Array.isArray (Branches) "или флаг, который установлен в computed-методе (" syncedBranches "), но ни один из них, похоже, не делает этого.
Как отложить рендеринг этого списка до тех пор, пока «Ветви» не будут заполненным массивом объектов? Разве я не должен использовать вычисленную переменную var и передавать данные получателем?
Главный компонент
<branches-widget-tabs :items="register" :activeItem="activeRegister">
<template #tabbody_0="Branches" >
<h1>Content Register 1</h1>
<branches-widget-list :items="Branches" v-if="syncedBranches"></branches-widget-list>
</template>
<template #tabbody_1="Branches" v-if="Array.isArray(Branches)">
<h1>Content Register 2</h1>
<branches-widget-list :items="Branches" v-if="syncedBranches"></branches-widget-list>
</template>
</branches-widget-tabs>
</div>
</template>
<style>
#branchesWidget {
min-width: 150px;
min-height: 150px;
background-color: #333;
}
#branchesWidget:hover {
background-color: #666;
}
</style>
<script>
import chroma from 'chroma-js';
//console.log('chroma',chroma);
import HUSL from 'hsluv';
//console.log('HUSL',HUSL);
import BranchesWidgetTabs from './BranchesWidgetTabs';
import BranchesWidgetList from './BranchesWidgetList';
const random = function(min, max){
return Math.floor(Math.random() * (max - min + 1)) + min;
};
var generateColors = function(n, startHex = '#ff6000', padding = 0, step = 5, randomSat = true, randomLight = true){
let colors = [];
const baseHex = HUSL.hexToHsluv(startHex);
const baseHue = baseHex[0];
//console.log('baseHue',baseHue);
var degrees = [];
for (let i = 0; i < n; i++) {
degrees.push( 360 / n * i);
}
//console.log('degrees',degrees);
const hues = degrees.map((offset) => {
return (baseHue + offset) % 360;
});
//console.log('hues',hues);
if(randomSat){
var baseSaturation = random(55, 85);
}else{
var baseSaturation = baseHex[1];
}
if(randomLight){
var baseLightness = random(35, 75);
}else{
var baseLightness = baseHex[2];
}
var subs = Math.min(n,Math.max(step,2));
for(let i = 0; i < subs; i++) {
colors.push( HUSL.hsluvToHex([
hues[i],
baseSaturation,
baseLightness
]));
}
console.log('colors',colors);
return chroma.scale(colors).padding(0).mode('lab').colors(n);
};
export default {
name: 'BranchesWidget',
props : [],
data() {
return {
activeRegister : null,
register : [
{
'title' : 'tab1',
}
,
{
'title' : 'tab2',
}
],
rawBranches : null,
syncedBranches : false
}
},
computed: {
Branches : function(){
if(this.rawBranches !== null){
let colorArr = generateColors(this.rawBranches.length);
console.log('colorArr',colorArr);
// Der Liste der Branchen die Farben zuordnen und als "Branches" bereitstellen
var l = [];
for(var i=0;i<this.rawBranches.length;i++){
var c = JSON.parse(JSON.stringify(this.rawBranches[i]));
c.color = colorArr[i];
l.push(c);
}
console.log('compute Branches',l);
this.syncedBranches = true;
return l;
}
console.log('compute Branches',null);
return null;
}
},
components: {
BranchesWidgetTabs,
BranchesWidgetList
},
mounted () {
axios
.post('/assets/get',{ entity : 'industryBranches' })
.then(response => ( this.rawBranches = response.data.data ))
},
created(){
//console.log('created',this.rawData);
},
methods : {
// das die Componenten eine ref mit der Bezeichnung "bwidget" hat, ist die Methode in der Seite mit app.$refs.bwidget.getBranches() erreichbar.
getBranches : function(){
return this.Branches;
}
}
}
</script>
Tabs-Compoent
<template>
<div class="BranchesWidgetTabs">
<div class="menu">
<div class="item" v-for="(item, index) in list">
<div>
<div class="i">
<div v-if="item.active">active</div>
</div>
<div class="title">
{{ item.title }}
</div>
</div>
</div>
<div class="spacer"></div>
</div>
<div class="tabbody" v-for="(item, index) in list">
<div class="content" v-if="item.active">
<slot :name="`tabbody_${index}`"></slot>
</div>
</div>
</div>
</template>
<style>
div.BranchesWidgetTabs {
background-color: yellow;
min-height: 40px;
}
div.BranchesWidgetTabs > div.menu {
display: flex;
flex-direction: row;
}
div.BranchesWidgetTabs > div.menu > .item {
flex: 0 0 auto;
min-width: 10px;
background-color: blue;
color: white;
}
div.BranchesWidgetTabs > div.menu > .item > div {
display: flex;
flex-direction: column;
padding: 0px 20px;
}
div.BranchesWidgetTabs > div.menu > .item:nth-child(odd) > div {
padding-right: 0;
}
div.BranchesWidgetTabs > div.menu > .item > div > div {
flex: 1;
}
div.BranchesWidgetTabs > div.menu > .item > div > div.i {
background-color: darkgrey;
min-height: 10px;
}
div.BranchesWidgetTabs > div.menu > .item > div > div.title {
background-color: pink;
padding: 10px 20px;
}
div.BranchesWidgetTabs > div.menu > .spacer {
flex: 1;
}
</style>
<script>
export default {
name: 'BranchesWidgetTabs',
props : {
items : Array,
activeItem : {
required : true,
validator: function(i){
return typeof i === 'number' || i === null;
}
},
},
data(){
return {
}
},
computed: {
list: function(){
var l = [];
var s = (this.activeItem !== null)? this.activeItem : 0;
for(var i=0;i<this.items.length;i++){
var c = JSON.parse(JSON.stringify(this.items[i]));
if(s === i){
c.active = true;
}else{
c.active = false;
}
l.push(c);
}
return l;
}
},
created(){
console.log('created',this.activeItem);
}
}
</script>
List-Component, который восстанавливает элементы из основного компонента
<template>
<div class="BranchesWidgetList">
Liste
</div>
</template>
<style>
div.BranchesWidgetList {
}
</style>
<script>
export default {
name: 'BranchesWidgetList',
props : {
items : Array
},
data(){
return {
}
},
computed: {
},
created(){
console.log('created BranchesWidgetList',this.items);
}
}
</script>
РЕДАКТИРОВАТЬ: Я понял! Каким-то образом я получил ошибку из-за директивы v-slot. Я подумал, что должен будет передать массив Branches-Array до дочернего компонента. Но кажется, что контекст Шаблон и основной компонент являются общими. Поэтому единственное, в чем нужно убедиться, это то, что asyn c -call для этого массива завершен с использованием "Branches.length" в v-if - не нужно дополнительных переменных, таких как "syncedBranches".
Полный основной компонент с работающим код.
<template>
<div id="branchesWidget">
<branches-widget-tabs :items="register" :activeItem="activeRegister">
<template #tabbody_0 v-if="Branches.length">
<h1>Content Register 1</h1>
<branches-widget-list :items="Branches"></branches-widget-list>
</template>
<template #tabbody_1 v-if="Branches.length">
<h1>Content Register 2</h1>
<branches-widget-list :items="Branches"></branches-widget-list>
</template>
</branches-widget-tabs>
</div>
</template>
<style>
#branchesWidget {
min-width: 150px;
min-height: 150px;
background-color: #333;
}
#branchesWidget:hover {
background-color: #666;
}
</style>
<script>
import chroma from 'chroma-js';
//console.log('chroma',chroma);
import HUSL from 'hsluv';
//console.log('HUSL',HUSL);
import BranchesWidgetTabs from './BranchesWidgetTabs';
import BranchesWidgetList from './BranchesWidgetList';
const random = function(min, max){
return Math.floor(Math.random() * (max - min + 1)) + min;
};
var generateColors = function(n, startHex = '#ff6000', padding = 0, step = 5, randomSat = true, randomLight = true){
let colors = [];
const baseHex = HUSL.hexToHsluv(startHex);
const baseHue = baseHex[0];
//console.log('baseHue',baseHue);
var degrees = [];
for (let i = 0; i < n; i++) {
degrees.push( 360 / n * i);
}
//console.log('degrees',degrees);
const hues = degrees.map((offset) => {
return (baseHue + offset) % 360;
});
//console.log('hues',hues);
if(randomSat){
var baseSaturation = random(55, 85);
}else{
var baseSaturation = baseHex[1];
}
if(randomLight){
var baseLightness = random(35, 75);
}else{
var baseLightness = baseHex[2];
}
var subs = Math.min(n,Math.max(step,2));
for(let i = 0; i < subs; i++) {
colors.push( HUSL.hsluvToHex([
hues[i],
baseSaturation,
baseLightness
]));
}
console.log('colors',colors);
return chroma.scale(colors).padding(0).mode('lab').colors(n);
};
export default {
name: 'BranchesWidget',
props : [],
data() {
return {
activeRegister : null,
register : [
{
'title' : 'tab1',
}
,
{
'title' : 'tab2',
}
],
rawBranches : null
}
},
computed: {
Branches : function(){
var l = [];
if(this.rawBranches !== null){
let colorArr = generateColors(this.rawBranches.length);
//console.log('colorArr',colorArr);
// Der Liste der Branchen die Farben zuordnen und als "Branches" bereitstellen
for(var i=0;i<this.rawBranches.length;i++){
var c = JSON.parse(JSON.stringify(this.rawBranches[i]));
c.color = colorArr[i];
l.push(c);
}
}
console.log('compute Branches',l);
return l;
}
},
components: {
BranchesWidgetTabs,
BranchesWidgetList
},
mounted () {
axios
.post('/assets/get',{ entity : 'industryBranches' })
.then(response => ( this.rawBranches = response.data.data ))
},
created(){
//console.log('created',this.rawData);
},
methods : {
getBranches : function(){
return this.Branches;
}
}
}
</script>