2017-06-18 74 views
0

我想在默認範圍內顯示一個變量。此版本的作品。VueJS Slot v-text

<slot>{{namedSlotText}}</slot> 

但是當我嘗試這種方式時,變量不顯示。

模板

<div id="app"> 
    <my-component></my-component> 
</div> 

代碼

let vm = new Vue({ 
    el:"#app", 
    components:{  
    myComponent:{ 
     template:` 
     <div> 
     <slot :text="namedSlotText"></slot> 
     </div> 
     `, 
     data:()=>({ 
     namedSlotText: "This is default slot text" 
     }) 
    } 
    } 
}) 

我看到一些地方v-text作品。

+0

槽超出範圍。數據只能在#app el內訪問。 – SaJed

+0

我的數據函數裏面的myComponent和數據不可訪問#app中只有accesible myComponent裏面 –

回答

0

避免使用用於數據箭頭功能,正確ES2015語法(內部部件)是:

data() { 
    return { 
    namedSlotText: "This is default slot text" 
    } 
} 

因爲使用的是標準插槽可以設置默認值,如下所示:

Vue.component('my-component', { 
    template: `<div><slot>{{slotText}}</slot></div>`, 
    data() { 
    return { 
     slotText: "This is default slot text" 
    } 
    } 
}) 

這裏的的jsfiddle:https://jsfiddle.net/va438nqk/

+0

不,我認爲可能問題不明白,你告訴答案改變數據方法,但我在我的問題中說 {{namedSlotText}}是工作,但不工作這意味着它不是數據問題,如果數據是內部組件是必須的功能 –

+0

啊我看到你想做什麼,我錯過了你使用的組件。你只是使用一個標準插槽,所以你可以通過在插槽之間放置文本來設置默認值:https://jsfiddle.net/va438nqk/ –

+0

是的,我知道我問爲什麼看起來像那個例子https://jsfiddle.net/tL88259x /不工作? –

2

當你傳遞一個屬性到slot,基本上你正在使用爲U數據由插槽的內容sed。這個概念被稱爲scoped slots

此代碼

<div> 
    <slot :text="namedSlotText"></slot> 
</div> 

使得提供給由所述槽的內容所使用的text屬性。爲了使用該屬性,您必須首先定義一個範圍模板,然後明確引用內容中的屬性。

<my-component> 
    <template scope="{text}"> 
    {{text}} 
    </template> 
</my-component>