Reputation: 123
I have a vuejs component in a html that is returned from jquery ajax call but it doesn't render the component. so how to make vuejs render this component from jquery?
jquery code sample :
$.post(baseURL + "media", postData, function (data) {
if(data.status == true) {
$('#media_lib_app').html(data.view);
}
});
and what is returned inside the data.view is :
<test-component></test-component>
but when the data.view is added to the html div it doesn't render the component.
Upvotes: 3
Views: 6446
Reputation: 3343
If I understand correctly you get a tag of a custom component from your AJAX call and want to build a Vue component out of it.
So let's say this is your <test-component>
:
Vue.component('test-component', {
template: "<p>I am the test component template</p>",
methods: {
// Component logic...
}
});
Now somewhere in your app, you make the AJAX call:
$(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));
})
Your component mounting point:
<div id="media_lib_app"></div>
More about .compile:
https://v2.vuejs.org/v2/api/#Vue-compile
Note: Vue.compile()
is only available in the full build.
You can find here an working example:
https://jsbin.com/motuvokeha/edit?html,js,output
Hope this can help you :)
Upvotes: 9