如何在jquery中动态添加的html中呈现vuejs组件 [英] how to render vuejs components in dynamically added html from jquery

查看:1087
本文介绍了如何在jquery中动态添加的html中呈现vuejs组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在jQuery ajax调用返回的html中有一个vuejs组件,但它不呈现该组件.那么如何使vuejs从jquery渲染此组件?

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代码示例:

jquery code sample :

$.post(baseURL + "media", postData, function (data) {
      if(data.status == true) {
           $('#media_lib_app').html(data.view);
      }
 });

,data.view内部返回的是:

and what is returned inside the data.view is :

<test-component></test-component>

但是当data.view添加到html div中时,它不会呈现该组件.

but when the data.view is added to the html div it doesn't render the component.

推荐答案

如果我正确理解,您会从AJAX调用中获得自定义组件的标签,并希望从中构建Vue组件.

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.

所以我们说这是您的<test-component>:

Vue.component('test-component', {
  template: "<p>I am the test component template</p>",
  methods: {
      // Component logic...
  }
});

现在在应用程序中的某个位置,您会进行AJAX调用:

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));
})

您的组件安装点:

<div id="media_lib_app"></div>

有关.compile的更多信息:

More about .compile:

https://vuejs.org/v2/api/#Vue-compile

注意: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 :)

这篇关于如何在jquery中动态添加的html中呈现vuejs组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆