如何在 Vue 中编译从外部 api 加载的模板

How to compile template loaded from external api in Vue

我有一个非 SPA 网络应用程序,它有 Vue 个组件并且运行良好。但是,我正在寻找一种通过外部 API.

加载包含 Vue 的 HTML 的方法

因此,我只需调用 /ajax/dialogbox/client/add 即可返回包含 Vue 组件的 HTML,例如:

<h1>Add client</h1>
<div>My static content</div>
<my-component></my-component>

但显然<my-component></my-component>没有做任何事情。 在 Angular 1 中,我使用 $compile 服务在输出前编译 HTML。

有没有办法在 Vue 中做同样的事情?

Vue 中有一个 compile function 可以编译模板来渲染函数。使用编译后的函数需要比您提供的更多的细节(例如,如果您需要将返回的模板与数据一起使用),但这里有一个例子。

console.clear()

Vue.component("my-component",{
  template: `<h1>My Component</h1>`
})

const template = `
<div>
<h1>Add client</h1>
<div>My static content</div>
<my-component></my-component>
</div>
`

new Vue({
  el: "#app",
  data:{
    compiled: null
  },
  mounted(){
    setTimeout(() => {
      this.compiled = Vue.compile(template)
    }, 500)
    
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.js"></script>
<div id="app">
  <component :is="compiled"></component>
</div>

请注意,在示例中,我将您的示例模板包装在 div 标记中。 Vue 要求 Vue 或组件只有一个根元素。

几个小时后,我设法将一些属性传递给要编译的组件。

在HTML正文中:

<!-- some where in the HTML body -->
<div id="vCard2">
   <component :is="compiled"></component>
</div>

<script>
var vmCard2 = new Vue({
  el: '#vCard2',
  data: {
    compiled: null,
    status: ''
  },
  methods: {
    show: function () {
      // macro is some dynamic string content or html template that contains mustache
      var macro = this.status == 'some_switch' ? '...{{payment.status}}...' : '...{{refund.status}}...';
      Vue.component('cp-macro', {
        data: function () {
          return {
            payment: vmCard1.payment,
            refund: vmCard1.refund
          }
        },
        template: '<span>'+macro+'</span>'
      })
      this.compiled = Vue.compile('<cp-macro></cp-macro>');
    },
    hide: function () {
      this.compiled = null; // must remove for the next macro to show
    }
  }
})
</script>