如何动态呈现vue.js组件?

时间:2017-03-24 19:29:45

标签: javascript components vue.js

有没有人知道动态渲染vue.js组件的方法?例如,我有一个表组件,它应该根据prop定义呈现不同的按钮:

Vue.component('my_table', {
    template: '#my_table',
    props: {
      data: Array,
      columns: Array,
      actions: Array
    }
});

理想情况下,我的模板会在tmpl对象的action值中定义:

<tbody>
    <tr v-for="entry in data">
      <td v-for="key in columns">
        {{entry[key.field]}}
      </td>
      <td v-for="action in actions">
        {{ action.tmpl }}
      </td>
    </tr>
</tbody>

这是我的小提琴:

https://jsfiddle.net/zfya92dh/43/

有人有什么想法吗?

提前致谢!

2 个答案:

答案 0 :(得分:1)

<component :is="action.tmpl"></component>

这是你的小提琴revised

const button1 = Vue.extend({
    template:'<button class="btn btn-primary">View</buttton>'
})

const button2 = Vue.extend({
  template:'<button class="btn btn-primary" @click="some_method">Delete</buttton>',
  methods:{
     some_method(){
         alert('clicked')
     }
  }
})

以及相关数据。

 data: {
    actions: [
    {
      name: 'view',
      label: 'View Company',
      method: 'click',
      tmpl: button1
    },
    {
      name: 'delete',
      label: 'Delete Company',
      method: 'click2',
      tmpl: button2
    },
  ],

答案 1 :(得分:1)

您只想插入HTML而不是纯文本?变化

<td v-for="action in actions">
    {{ action.tmpl }}
</td>

<td v-for="action in actions" v-html="action.tmpl"></td>

但是,如果您的HTML包含Vue标记,则不会遵循标记。您需要创建实际组件来表示每个配置,然后使用:is告诉Vue在给定时间使用哪个组件。 Vue不使用基于字符串的模板,因此无法使模板字符串传递起作用。

相关问题