[英]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.