我在从 jquery ajax 调用返回的 html 中有一个 vuejs 组件,但它不呈现该组件。那么如何让 vuejs 从 jquery 渲染这个组件呢?
jquery 代码示例:
$.post(baseURL + "media", postData, function (data) {
if(data.status == true) {
$('#media_lib_app').html(data.view);
}
});
data.view 中返回的是:
<test-component></test-component>
但是当 data.view 添加到 html div 时,它不会呈现组件。
最佳答案
如果我理解正确的话,您从 AJAX 调用中获得了一个自定义组件的标签,并希望从中构建一个 Vue 组件。
假设这是您的 <test-component>
:
Vue.component('test-component', {
template: "<p>I am the test component template</p>",
methods: {
// Component logic...
}
});
现在在您应用的某处,您进行 AJAX 调用:
$(document).ready(function() {
var html = '<test-component></test-component>';
var url = "https://jsonplaceholder.typicode.com/posts";
$.get(url, function (data) {
var res = Vue.compile(html)
new Vue({
render: res.render,
staticRenderFns: res.staticRenderFns
}).$mount('#media_lib_app')
}.bind(this));
})
您的组件安装点:
<div id="media_lib_app"></div>
关于 .compile 的更多信息:
https://v2.vuejs.org/v2/api/#Vue-compile
注:Vue.compile()
仅在完整版本中可用。
你可以在这里找到一个工作示例:
https://jsbin.com/motuvokeha/edit?html,js,output
希望对你有帮助:)
关于javascript - 如何在 jquery 动态添加的 html 中呈现 vuejs 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45549918/