【发布时间】:2018-01-11 20:46:31
【问题描述】:
我是 Vue 的新手,但我遇到了问题。我已经搜索过了,但我想我的大脑一定是疯了,因为我不知道如何正确表达这个词。
我有这样的设置:
Vue.component('custom-component', {
template: '<div><slot></slot></div>',
data: function() {
return {
parent_data: [1, 2, 3, 4, 5]
}
}
});
Vue.component('sub-component', {
props: {
dataProp: {
default: []
}
},
data: function() {
return {
data: []
}
},
template: '<div class="subs">{{data.length}}<slot></slot></div>',
mounted: function() {
this.data = this.dataProp;
}
});
new Vue({
el: '#root'
});
<script src="https://unpkg.com/vue@2.4.2"></script>
<div id="root">
<custom-component>
hello
<sub-component>
sub component hello
</sub-component>
</custom-component>
</div>
注意parent_data 属性实际上是在 ajax 调用中通过 Vue Resource 定义的,尽管这似乎与此无关。
您会看到我们在浏览器中得到“hello 0 sub component hello”输出。好的,酷。所以我想我会摆弄它并尝试将一些文本放入组件的文本槽中,如下所示:
Vue.component('custom-component', {
template: '<div><slot></slot></div>',
data: function() {
return {
parent_data: [1, 2, 3, 4, 5]
}
}
});
Vue.component('sub-component', {
props: {
dataProp: {
default: []
}
},
data: function() {
return {
data: []
}
},
template: '<div class="subs"><slot></slot></div>',
mounted: function() {
this.data = this.dataProp;
}
});
new Vue({
el: '#root'
});
<script src="https://unpkg.com/vue@2.4.2"></script>
<div id="root">
<custom-component>
hello
<sub-component>
{{data.length}}sub component hello
</sub-component>
</custom-component>
</div>
但这不再像我预期的那样有效。为了使这个示例正常工作,我必须做什么?
这个问题更接近现实的部分看起来像这样:
Vue.component('custom-component', {
template: '<div><slot></slot></div>',
data: function() {
return {
parent_data: [1, 2, 3, 4, 5]
}
},
mounted: function() {
//this.$http.get('/page/here').then(results=> this.parent_data = results, console.error );
}
});
Vue.component('sub-component', {
props: {
dataProp: {
default: []
}
},
data: function() {
return {
data: []
}
},
template: '<div class="subs"><slot></slot></div>',
mounted: function() {
this.data = this.dataProp;
}
});
new Vue({
el: '#root'
});
<script src="https://unpkg.com/vue@2.4.2"></script>
<div id="root">
<custom-component>
hello
<sub-component :data-prop="parent_data">
{{data.length}} sub component hello
</sub-component>
</custom-component>
</div>
提前致谢!
【问题讨论】:
标签: vuejs2 vue-component