我正在努力遵循vuejs应用场景动态组件+异步组件模式。 一切正常,但仍然只有一个问题: 如何通过
访问传入的道具数据<component :is="asyncComp" opts="someDataForAsyncComp">
请看现场小提琴: https://jsfiddle.net/matiascx/wjab87om/8/
以下是代码:
<div id="app">
by dynamic Component:
<component
v-for="item in items"
:is="item.component"
:opts="item.options"> <!-- can we give props data to async component here? -->
</component><div>
以下是js部分:
Vue.component('node3', function (resolve, reject) {
setTimeout(function () {
resolve({
template: '<div>I am async node3!</div>',
created: function(){
console.log(this.opts); // can we access props transferred into async component via component
}
})
}, 1000)
})
Vue.component('node', {
template: '<div>must be static tpl!</div>',
props: ['opts'],
computed: {
log: function() {
return JSON.stringify(this.opts);
}
},
data() {
return {}
},
created: function(){
console.log(this.opts);
}
});
Vue.component('node2', {
template: '<div>node2</div>',
props: ['opts'],
computed: {
log: function() {
return JSON.stringify(this.opts);
}
},
data() {
return {}
},
created: function(){
console.log("dfdsfsdfa");
}
});
new Vue({
el: '#app',
data() {
return {
newItem: {
component: "",
options: ""
},
items: [{
component: "node",
options: {
type: "node",
tpl: "<div>node: {{ opts }} {{ log }}</div>"
}
},
{
component: "node2",
options: {
type: "node2",
tpl: "<div>node2: {{ opts }} {{ log }}</div>"
}
},
{
component: "node3",
options: {
type: "node3",
tpl: "<div>node3: {{ opts }} {{ log }}</div>"
}
}
]
};
},
computed: {
isButtonDisplayed() {
return this.newItem.component && this.newItem.options
}
},
methods: {
addItem() {
this.items.push(this.newItem);
this.newItem = {
component: "",
options: ""
}
}
}
});
答案 0 :(得分:2)
我在你的jsfiddle中加了三行:
// dynamic component
var _this = this
this.$nextTick(()=>{console.log(JSON.stringify(_this.$options._parentVnode.data.attrs.opts))})
// static component
console.log(JSON.stringify(this.$options.propsData.opts))
https://jsfiddle.net/gurghet/wjab87om/11/
我不认为这是最好的方式,但最好还是问Evan。