然而,这已经不可能了,Vue 2
是数据驱动的,因此您根本不应该尝试手动影响 DOM,而是应该将元素绑定到视图模型中的基础数据。考虑到这一点,您的示例将需要重写。首先,首先将您的元素设为component
:
Vue.component('my-button', {
template: '<button v-on:click="test()">{{text}}</button>',
props: ['text'],
methods: {
test() {
alert('Test');
}
}
});
然后您可以创建主视图模型并使用 v-for 添加按钮组件:
Markup:
<button v-on:click="addNewElement()">Add Element</button>
<my-button v-for="button in buttons" :text="button"></my-button>
查看型号:
new Vue({
el: '#app',
methods: {
addNewElement: function() {
this.buttons.push('Test');
}
},
data: {
buttons: []
}
});
在此示例中,我们将按钮推送到一个数组,然后该数组将显示在页面上,而不是手动将它们附加到模板中。
这是 JSFiddle:http://jsfiddle.net/10q9je5a/ http://jsfiddle.net/10q9je5a/
如果你想要更通用的东西,那么你可以简单地创建一个数组different components
并使用:is
让 Vue 知道要渲染哪个组件:
Markup:
<div id="app">
<button v-on:click="addNewElement()">Add Element</button>
<div :is="element.component" v-for="element in elements" v-bind="element.props"></div>
</div>
查看型号:
new Vue({
el: '#app',
methods: {
addNewElement: function() {
this.elements.push({component: 'my-button', props: {text: 'Test'}});
}
},
data: {
elements: []
}
});
这是 JSFiddle:http://jsfiddle.net/cxo5eto0/ http://jsfiddle.net/cxo5eto0/