您应该让数据驱动视图。
换句话说,假设您有以下 html:
<div id="app">
<component></component>
<!-- the following ones are inserted via ajax -->
<component></component>
<component></component>
</div>
和js:
var app = new Vue({
el: '#app',
data: {
foo: 'bar',
}
})
您可能正在发出 ajax 请求并将 <component></component> 手动插入到 html 中。这不是你应该使用 Vuejs 的方式。
让数据驱动视图的方式是创建所需的数据:
var app = new Vue({
el: '#app',
data: {
foo: 'bar',
components: [
{}, //component related data
...
]
},
components: {
component,
},
ajaxRequest() {
//this should push into your components array
// example:
$.ajax().done(function(data) {
this.components.push(data);
})
}
})
在这段代码中,我向data 添加了一个新数组(components),它将存储我想要在我的视图中呈现的组件。当我通过 ajax 获取组件时,我将它们添加到这个数组中。现在,如果我将 html 更改为:
<div id="app">
<component v-for="component in components" data="component">
</component>
</div>
每当components 数组更新时,Vue 都会自动将它们添加到视图中。