簡體   English   中英

如何動態渲染 vue.js 組件?

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

有人知道動態渲染 vue.js 組件的方法嗎? 例如,我有一個表格組件,它應該根據道具定義呈現不同的按鈕:

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

理想情況下,我的模板將在我的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>

這是我的小提琴:

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

有人有想法么?

提前致謝!

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

這是您修改過的小提琴。

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
    },
  ],

您只想插入 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 不使用基於字符串的模板,因此無法使傳遞模板字符串起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM