你应该让你的数据驱动视图。
换句话说,让我们假设你有以下的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);
})
}
})
在这段代码中,我添加了一个新的数组(components
)的data
将存储我想在我看来渲染的组件。当我通过ajax获取组件时,我将它们添加到这个数组中。现在,如果我更改HTML到:
<div id="app">
<component v-for="component in components" data="component">
</component>
</div>
每当components
阵列更新,Vue公司会自动将它们添加到视图。
我们可以看到一些代码吗?不太清楚你在做什么。 – Bert