3
votes

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.

1
Can you show your code? - thanksd
the actual code is too big as its an old project that was relying on jquery but this is the exact situation as explained in the post - m_elbardeny
You'll be more likely to get help if you can provide a Minimal, Complete, and Verifiable example of your issue. - thanksd
ok i'll edit the post to add some code :) - m_elbardeny

1 Answers

9
votes

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://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 :)