[英]Vue slot-scope is not working inside grandchildren elements
Given the following component configuration:鉴于以下组件配置:
Vue.component('myComponent', {
data () {
return {
msg: 'Hello',
}
},
template: `
<div class="my-component">
<slot :msg="msg"></slot>
</div>
`,
})
Calling out the component from a template like this, doesn't bind the msg
value inside the grand-child
element:从这样的模板中调用组件,不会在grand-child
元素内绑定msg
值:
<my-component>
<div class="parent">
<div class="child">
<div class="grand-child" slot-scope="{ msg }">
{{ msg }}
</div>
</div>
</div>
</my-component>
Is slot-scope
restricted to direct child element, and why? slot-scope
仅限于直接子元素,为什么?
Is slot-scope restricted to direct child element, and why? slot-scope 是否仅限于直接子元素,为什么?
Yes.是的。 This is because the <slot>
element within the component is replaced with the content passed in. When Vue finds the slot-scope
attribute on the component content element (ie, your <div class="parent">
), it binds all the v-bind
attributes found in the <slot>
to that namespace.这是因为组件内的<slot>
元素被传入的内容替换了。 当 Vue在组件内容元素(即你的<div class="parent">
)上找到slot-scope
属性时,它会绑定所有的在<slot>
找到的v-bind
属性到该命名空间。
For example例如
Vue.component('myComponent', { data () { return { msg: 'Hello', } }, template: ` <div class="my-component"> <slot :msg="msg"></slot> </div> `, }) new Vue({el: '#app'})
.parent, .child, .grand-child { border: 1px solid; padding: 2px; } .parent:before, .child:before, .grand-child:before { content: attr(class); display: block; color: #999; font-size: 0.8em; }
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.min.js"></script> <div id="app"> <my-component> <div class="parent" slot-scope="{ msg }"> <div class="child"> <div class="grand-child"> {{ msg }} </div> </div> </div> </my-component> </div>
To attempt to explain further, consider that Vue treats all HTML elements as render functions.为了进一步解释,请考虑 Vue 将所有 HTML 元素视为渲染函数。 With this in mind, it looks at the <slot>
element and what is bound to it.考虑到这一点,它会查看<slot>
元素以及绑定到它的内容。 When it replaces the <slot>
with the content provided to the component, it looks at that root element when deciding what attributes to evaluate and what data to bind.当它用提供给组件的内容替换<slot>
时,它会在决定评估哪些属性和绑定哪些数据时查看该根元素。 It does not look down into that element's hierarchy.它不会向下看那个元素的层次结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.