2016-04-21 107 views
0

作爲一個簡單的例子假設你在一個名爲「我的-按鈕」部分有這樣的:插槽:訪問範圍變量

<button v-for='item in items' v-on:click="this.$emit('activate', item)"> 
    <slot>{{ item.name }}</slot> 
</button> 

如果我使用的組件在其他地方,有沒有什麼辦法來覆蓋槽訪問item.name值?例如:

<my-component items="myItems"> 
    <span class="myspecialstuff">{{ item.name }}</span> 
</my-component> 

顯然因爲目前的情況是,VUE將抱怨找不到範圍item

回答

0

UPDATE2: 下面的代碼無法正常工作,由於https://github.com/vuejs/vue/issues/2511。我想不出別的什麼。抱歉。

UPDATE:

爲了實現特定插槽壓倒一切的,定義插槽,

<button v-for='item in items' v-on:click="this.$emit('activate', item)"> 
    <slot v-bind:name="'item-'+item.name">{{ item.name }}</slot> 
</button> 

並重寫爲

<my-component items="myItems"> 
    //you have access to items so you can do this 
    //specialItems is an array of items which are to be overriden 
    <span class="myspecialstuff" v-for="item in specialItems" v-bind:slot="'item-'+item.name" > 
     {{ item.name }} 
    </span> 
</my-component> 

原來的答覆: 那會很費解恕我直言。

有兩種方法可以達到你想要的效果,這取決於<my-component在哪裏得到items

  1. items作爲道具傳遞給my-component。 (最常見的情況)。在這種情況下,您已經可以訪問items,並且不需要爲此跳過。

  2. <my-component>通過像表格或API一些外部資源越來越items。(不太可能)在這種情況下,您可以raise events to pass data或使用2-way bindings通過.sync

+0

我的確有機會獲得物品數組在「我的組件」的範圍內,但我沒有訪問for循環中的當前選定項目,這是我需要更新插槽內容。 – nablex

+0

說,你實際上是否使用你在這裏發佈的確切代碼?因爲它幾乎沒有問題。訪問特定指數的方式與你實現它的方式各不相同, –

+0

這是我在用的一個簡單的例子,不知道什麼是錯的(假設項目是一個數組)?它的工作原理也是如此,它只是失敗插槽的重寫。 – nablex