Vue pass slot template to extended component

前端 未结 5 1583
Happy的楠姐
Happy的楠姐 2021-01-12 02:24

Is any way to pass a template to extended component? Example, that illustrates the problem:

There is a component named Slide with a template like so:

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-12 02:48

    You can use Vue.compile combined with $createElement.

    const slotTemplate = `

    This is the slot content

    {{message}}
    `; const renderer = Vue.compile(slotTemplate) const slotContent = { data(){ return { message: "some data in the slot" } }, render: renderer.render, staticRenderFns: renderer.staticRenderFns } const instance = new Slide(); instance.$slots.default = [instance.$createElement(slotContent)]; instance.$mount("#container");

    Above is an example of a slot that requires some data. If your slot content is just HTML you could get away with just this:

    const slotTemplate = `

    This is the slot content

    ` const instance = new Slide(); instance.$slots.default = [instance.$createElement(Vue.compile(slotTemplate))]; instance.$mount("#container");

    Here is an example.

    Note: $slots[key] should be an array of vNodes. It will render correctly if you use a vNode, but there will be bugs (e.g. when calling vm._update)

提交回复
热议问题