【问题标题】:How to compile template loaded from external api in Vue如何在 Vue 中编译从外部 api 加载的模板
【发布时间】:2017-12-06 01:56:13
【问题描述】:

我有一个非 SPA 网络应用程序,它包含 Vue 组件并且效果很好。但是,我正在寻找一种通过外部 API 加载包含 Vue 的 HTML 的方法。

所以,我只需调用/ajax/dialogbox/client/add,它会返回包含Vue 组件的HTML,例如:

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

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

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

【问题讨论】:

    标签: compilation vue.js vue-component


    【解决方案1】:

    在 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 或组件只有一个根元素。

    【讨论】:

    • 如何传递 Props?
    • @PhilippMochine 最简单的方法是将它们添加到&lt;component :myprop="someValue" /&gt;
    • 只是渲染视图但是JS脚本控制器不能完全工作
    • 我尝试像这样&lt;component :is="compiled" :payment="payment"&gt;&lt;/component&gt; 传递道具,但它抛出错误[Vue 警告]:属性或方法“付款”未在实例上定义,但在渲染期间引用。通过初始化该属性,确保该属性是反应性的,无论是在数据选项中,还是对于基于类的组件。有什么想法吗?
    • @kiatng 这听起来就像你正在编译的任何东西都有一个叫做payment 的东西,它需要是已编译组件的属性。例如,您正在传递它,但在正在编译的组件上没有定义任何内容来接收它。
    【解决方案2】:

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

    在 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>
    

    【讨论】:

    • Thax 它帮助我缩小范围并在我的项目中使用它通过调用import 通过Vue.extand
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    • 2019-07-07
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    • 2011-09-06
    • 2019-11-11
    相关资源
    最近更新 更多