JSFiddle - React, Tailwind, and code Playground
by robert chang
HTML
<script src="https://cdn.jsdelivr.net/vue/latest/vue.js"></script>
<div id="app">
by dynamic Component:
<component
v-for="item in items"
:is="item.component"
:opts="item.options">
</component>
<!--
<br /> by directly ref Component:
<node :opts="items[1].options">
</node>
-->
<br />
<!--
<div>
Select a component type:
</div>
<div>
<label for="newItemNode">Node</label>
<input id="newItemNode" type="radio" value="node" v-model="newItem.component">
</div>
<div>
<label for="newItemNode2">Node 2</label>
<input id="newItemNode2" type="radio" value="node2" v-model="newItem.component">
</div>
<div>
<div>
Enter your options:
</div>
<label for="newItemOptions">Options</label>
<input id="newItemOptions" @keyup.enter="addItem" type="text" v-model="newItem.options">
</div>
<button v-if="isButtonDisplayed" @click="addItem">new item</button>
</div>
-->
JavaScript
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>', //这里this.opts是无法访问的,必须通过所谓async component才能够实现
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: ""
}
}
}
});