我有一个包装器组件,它只是一个通过默认插槽接受内容的<transition-group>组件。通过默认插槽传递的内容是一系列辅助vue组件。
由于转换组中的项需要设置键值,我该如何将键添加到槽项中?因为它们是分槽的,并且不会在v-for循环中呈现,所以我认为需要以编程方式添加键。
下面是一个可供使用的代码片段。您将在created()钩子中看到我的方法,它似乎在初始页面加载/呈现时有效,但是当我的dev环境中的热重载刷新时,键丢失,并且返回关于转换组子需要键的错误。
有没有更好的方法来实现这一点,让热重新加载保持愉快?也许我不应该担心热重新加载,因为它只是一个开发特性,但我的想法是,如果热重新加载不喜欢我的方法,那么我可能做得不正确,可能有更好的方法。
有什么想法?
我也很好奇,在生命周期中,什么时候是修改插槽节点的合适时机。此外,node.key是否是应用唯一密钥的正确位置?插槽节点中的哪个属性是要编辑的正确属性?(即,当在v-for循环中设置键时,在组件数据属性中也设置了' key‘)
非常感谢您能提供的任何见解!
Vue.component('wrapper-component', {
render(h) {
return h('transition-group', this.$slots.default)
},
// my attempt at providing a unique key for transition children is in created() hook below
// this works on itital page load/rendering - but breaks when hot-reload refreshes my development site
// uncomment created() hook to see my approach in action - works here on page reload, but does not hold up with hot-reload (i.e. once hot-reload refreshes, the transition items no longer have their unique keys)
/*
created() {
this.$slots.default = this.$slots.default.map((node, index) => {
node.key = `${node.tag}-${index}`
return node
})
}
*/
});
Vue.component('child-item', {
render(h) {
return h('div', this.$slots.default)
}
});
new Vue({
el: "#app"
});div {
display: block;
width: 100%;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<wrapper-component>
<child-item>My Child 1</child-item>
<child-item>My Child 2</child-item>
<child-item>My Child 3</child-item>
<child-item>My Child 4</child-item>
</wrapper-component>
</div>
发布于 2019-03-07 02:42:46
尝试添加beforeUpdate挂钩:
beforeUpdate() {
this.$slots.default = this.$slots.default.map((node, index) => {
node.key = `${node.tag}-${index}`
return node
})
}https://stackoverflow.com/questions/55028563
复制相似问题