您应该让数据驱动视图。
换句话说,假设您有以下 html:
<div id="app">
<component></component>
<!-- the following ones are inserted via ajax -->
<component></component>
<component></component>
</div>
and 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);
})
}
})
在此代码中,我添加了一个新数组(components
)到data
它将存储我想要在视图中渲染的组件。当我通过 ajax 获取组件时,我将它们添加到这个数组中。现在,如果我将 html 更改为:
<div id="app">
<component v-for="component in components" data="component">
</component>
</div>
每当components
数组更新后,Vue 会自动将它们添加到视图中。