Vue组件中的动态x模板

时间:2019-11-08 12:24:07

标签: vue.js vuejs2 vue-component

我有这个组件,并且想向该组件传递一个参数/属性,说明要使用哪个x模板。当我这样做时,它会失败:

JS:

Vue.component('custom-table', {
    props: ['template'],
    template: '#' + this.template
})
new Vue({ el: '#app' })

HTML:

<custom-table template="my-template"></custom-table>

<script type="text/x-template" id="my-template">
   <p>My Template</p>
</script>

错误:

vue.js:3 [Vue warn]: Cannot find element: #undefined

如何使用这样的动态模板?

2 个答案:

答案 0 :(得分:2)

我不确定这是否是个好主意,但确实与您的要求非常接近:

Vue.component('custom-table', {
  props: ['template'],
  template: `<component :is="{ template: '#' + template }" />`
})

new Vue({
  el: '#app'
})
<script src="https://unpkg.com/vue@2.6.10/dist/vue.js"></script>
<script type="text/x-template" id="button-template">
   <button>My Template</button>
</script>

<script type="text/x-template" id="em-template">
   <em>My Template</em>
</script>

<div id="app">
  <custom-table template="button-template"></custom-table>
  <custom-table template="em-template"></custom-table>
</div>

此处的技巧是使用is的对象版本,该版本允许您内联传递组件定义。严格来说,这里有两个组件,父母和孩子,x模板被分配给孩子。也就是说,生成的DOM应该是所希望的,因为父级不会自己添加任何额外的元素。

答案 1 :(得分:1)

您不能为单个组件提供动态模板。

您可以创建各种组件,然后动态选择要为特定标签呈现的组件。为此,Vue支持动态组件:

<component v-bind:is="currentTabComponentName"></component>

或者,如果希望调用者使用任意HTML填充组件的空白,则可以使用插槽。

https://vuejs.org/v2/guide/components-slots.html

或者,如果它只是静态HTML,则可以将HTML本身作为字符串传递,并在不转义的情况下呈现内容:

<div v-html="task.html_content"> </div>

也许其中一项适合您...

其他选项可能是使用渲染功能或JSX。

相关问题