[英]Slot: access scope variables
As a simplified example suppose you have this in a component called "my-buttons": 作为一个简化的示例,假设您在名为“ my-buttons”的组件中拥有此组件:
<button v-for='item in items' v-on:click="this.$emit('activate', item)">
<slot>{{ item.name }}</slot>
</button>
If I use the component somewhere else, is there any way to override the slot and access the item.name
value? 如果我在其他地方使用该组件,是否有任何方法可以覆盖插槽并访问item.name
值? For example: 例如:
<my-component items="myItems">
<span class="myspecialstuff">{{ item.name }}</span>
</my-component>
Obviously as it stands now, vue will complain that it can not find item
in the scope. 显然,vue会抱怨说它无法在合并范围内找到item
。
UPDATE2: the following code does not work due to https://github.com/vuejs/vue/issues/2511 . UPDATE2:由于https://github.com/vuejs/vue/issues/2511 ,以下代码无法正常工作。 I can't think of anything else. 我想不出什么了。 sorry. 抱歉。
UPDATE: 更新:
To achieve specific slot overriding, define slots as 要实现特定的广告位覆盖,请将广告位定义为
<button v-for='item in items' v-on:click="this.$emit('activate', item)">
<slot v-bind:name="'item-'+item.name">{{ item.name }}</slot>
</button>
and override as 并覆盖为
<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>
Original answer: that will be very convoluted imho. 原始答案:恕我直言,这是非常令人费解的。
there are 2 ways to achieve what you want depending on where <my-component
is getting items
. 有两种方法可以实现您想要的目标,具体取决于<my-component
在哪里获取items
。
items
is passed to my-component
as props. items
将作为道具传递到my-component
。 (most common case). (最常见的情况)。 In that case, you already have access to items
and do not need to jump through hoops for it. 在这种情况下,您已经可以访问items
,而无需为此而跳过。
<my-component>
is getting items
through some external sources like a form or api.(less likely) in this case, you can either raise events to pass data or use 2-way bindings through .sync
<my-component>
通过诸如Form或api之类的一些外部资源获取items
。(在这种情况下,不太可能)您可以引发事件以传递数据或通过.sync
使用2向绑定
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.