【发布时间】:2020-11-16 03:12:35
【问题描述】:
官方doc 说this.$children 没有反应,
当前实例的直接子组件。请注意,$children 没有订单保证,而且它不是响应式的......
因此,任何更改都不应触发任何重新渲染。 [this.$children api 已从 vuejs v3 中删除,因此它仅适用于 v2.x。]
我觉得这很有趣...https://codepen.io/tatimblin/pen/oWKdjR
上面沙盒中的代码是使用slot & this.$childen api 实现的tab UI 的演示。
最初tabs 组件持有对this.$children 数组的引用,这里有一个日志:
有趣的是,tab 的 isActive 属性正在使用该数组进行更改,但它反映在每个组件中,导致重新渲染..
我不确定这里发生了什么......也许我错过了一些东西。
模板:
<div id="root" class="container">
<tabs>
<tab name="Services" :selected="true">
<h1>What we do</h1>
</tab>
<tab name="Pricing">
<h1>How much we do it for</h1>
</tab>
<tab name="About Us">
<h1>Why we do it</h1>
</tab>
</tabs>
</div>
JS:
Vue.component('tabs', {
template: `
<div>
<div class="tabs">
<ul>
<li v-for="tab in tabs" :class="{ 'is-active': tab.isActive }">
<a :href="tab.href" @click="selectTab(tab)">{{ tab.name }}</a>
</li>
</ul>
</div>
<div class="tabs-details">
<slot></slot>
</div>
</div>
`,
data() {
return {tabs: [] };
},
created() {
this.tabs = this.$children;
},
methods: {
selectTab(selectedTab) {
this.tabs.forEach(tab => {
tab.isActive = (tab.name == selectedTab.name);
// this is how the isActive prop is changed, using this.$children
});
}
}
});
Vue.component('tab', {
template: `
<div v-show="isActive"><slot></slot></div>
`,
props: {
name: { required: true },
selected: { default: false}
},
data() {
return {
isActive: false
};
},
computed: {
href() {
return '#' + this.name.toLowerCase().replace(/ /g, '-');
}
},
mounted() {
this.isActive = this.selected;
}
});
new Vue({
el: '#root'
});
【问题讨论】:
-
"
tab的名称属性正在使用该数组进行更改"。在哪里?唯一的设置选项卡name道具是模板 -
@Dan my bad.. 我的意思是
isActiveporp..,我已经在评论中正确提到了道具正在改变的地方。
标签: vue.js vuejs2 vue-reactivity