简体   繁体   English

如何动态渲染 vue.js 组件?

[英]How to dynamically render vue.js components?

does anyone know of a way to dynamically render vue.js components?有人知道动态渲染 vue.js 组件的方法吗? For example, I have a table component that should render different buttons based on the prop definition:例如,我有一个表格组件,它应该根据道具定义呈现不同的按钮:

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

Ideally, my template would be defined in the tmpl value of my action object:理想情况下,我的模板将在我的action对象的tmpl值中定义:

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

Here's my fiddle:这是我的小提琴:

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

Anyone have any ideas?有人有想法么?

Thanks in advance!提前致谢!

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

Here is your fiddle 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')
     }
  }
})

And the relevant data.以及相关数据。

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

You just want to insert HTML instead of plain text?您只想插入 HTML 而不是纯文本? Change改变

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

to

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

However, if your HTML includes Vue markup, the markup will not be respected.但是,如果您的 HTML 包含 Vue 标记,则不会尊重该标记。 You will need to create actual components to represent each of your configurations and then use :is to tell Vue which one to use at a given time.您将需要创建实际的组件来表示您的每个配置,然后使用:is告诉 Vue 在给定时间使用哪个组件。 Vue doesn't use string-based templating, so there is no way to make passing a template string work. Vue 不使用基于字符串的模板,因此无法使传递模板字符串起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM