Vue组件和AJAX加载的HTML内容 [英] Vue Components and AJAX loaded HTML content
问题描述
我有一个Vue组件,基本上是复杂HTML标记的简写.
I have A Vue component which is basically a shorthand for complex HTML markup.
在初始加载时,一切正常.
On initial load, Everything works fine.
我正在使用AJAX将更多的这些组件加载到页面上,问题是该组件在加载了AJAX之后,不想被编译成HTML,我只能得到未渲染的Vue组件,如下所示:
I am using AJAX to load more of these components onto the page, The problem is that this component, after being loaded with AJAX, doesn't want to get compiled into HTML I only get the un-rendered Vue component like below:
< component>< slot>内容</slot></component>
我看过Vue.compile()和render函数,但无法弄清楚如何使它工作或如何重新渲染?组件.
I have looked at Vue.compile() and the render function but cannot figure out how to get this working or how to re-render? the components.
希望如此,任何人都可以阐明我在这里应该做什么吗?
Hope that makes sense, Can anyone shed some light on what I should be doing here?
推荐答案
您应该让数据驱动视图.
You should let your data drive the view.
换句话说,假设您具有以下html:
In other words, let's assume you have the following 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的方式.
You are probably making the ajax request and inserting manually the <component></component>
into the html. That's not the way you should work with Vuejs.
让数据驱动视图的方式是创建所需的数据:
The way you let your data drive the view is, well, creating the needed data:
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更改为:
In this code, I've added a new array (components
) to the data
that will store the components I want to render in my view. When I fetch components via ajax I add them to this array. Now, if I change the html to:
<div id="app">
<component v-for="component in components" data="component">
</component>
</div>
每 components
个数组更新时,Vue都会自动将它们添加到视图中.
whenever the components
array is updated, Vue will automatically add them to the view.
这篇关于Vue组件和AJAX加载的HTML内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!