2017-03-27 34 views
3

是否有任何方式將模板傳遞給擴展組件?例如,說明了這個問題:Vue將插槽模板傳遞給擴展組件

有一個與模板命名Slide像這樣組成:

<template> 
    <div class="swiper-slide swiper-slide-one"> 
     <div class="swiper-filter"></div> 
     <slot /> 
    </div> 
</template> 

在其他地方,我需要創建和安裝在必要的風格,成分:

import SlideComponent from '@/components/Slide' 
const Slide = Vue.extend(SlideComponent); 
new Slide().$mount('#container'); 

問題是,我不知道如何傳遞將在擴展組件的插槽中編譯的模板。

jsfiddle

回答

0

你要通過這樣的:

<Slide> 
    //HTML code here goes to slot 
</Slide> 
+0

我無法控制需要安裝組件的位置模板。所以問題是如何從代碼中傳遞插槽數據... – Kirill

+0

你能解釋一下你準確找到了什麼嗎? – SLYcee

1

如果你是開放的改變你的方法一點點,一的<component>代替<slot>

https://jsfiddle.net/jonataswalker/z5Lgbjv8/

const Parent = { 
    template: `<div> 
     <span>parent content</span> 
     <component :is="view"></component> 
    </div>`, 
    data() { 
    return { view: '' } 
    } 
} 

const Other = { 
    template: `<div> 
     <h1>from Other</h1> 
    </div>` 
} 

const Slide = Vue.extend(Parent) 

// how to pass template to the Parent`s slot? 
new Slide({ 
    data: { view: Other } 
}).$mount('#container') 
2

您可以將Vue.compile$createElement結合使用。

const slotTemplate = `<div><h4>This is the slot content</h4>{{message}}</div>`; 
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"); 

上面是一個需要一些數據的插槽示例。如果您的插槽的內容只是HTML,你可以擺脫眼前這個:

const slotTemplate = `<div><h4>This is the slot content</h4></div>` 
const instance = new Slide(); 
instance.$slots.default = [instance.$createElement(Vue.compile(slotTemplate))]; 
instance.$mount("#container"); 

這裏是一個example

注:$slots[key] should be an array of vNodes。它會正確渲染,如果你使用vNode,但會有錯誤(例如,當調用vm._update時)

+0

@Edd您的編輯被拒絕了,但我將它添加到了答案中。你是對的。 – Bert

相關問題