首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Vue -在渲染前修改插槽的适当方法-目标:以编程方式添加转换组密钥

Vue -在渲染前修改插槽的适当方法-目标:以编程方式添加转换组密钥
EN

Stack Overflow用户
提问于 2019-03-07 01:06:06
回答 1查看 1.2K关注 0票数 2

我有一个包装器组件,它只是一个通过默认插槽接受内容的<transition-group>组件。通过默认插槽传递的内容是一系列辅助vue组件。

由于转换组中的项需要设置键值,我该如何将键添加到槽项中?因为它们是分槽的,并且不会在v-for循环中呈现,所以我认为需要以编程方式添加键。

下面是一个可供使用的代码片段。您将在created()钩子中看到我的方法,它似乎在初始页面加载/呈现时有效,但是当我的dev环境中的热重载刷新时,键丢失,并且返回关于转换组子需要键的错误。

有没有更好的方法来实现这一点,让热重新加载保持愉快?也许我不应该担心热重新加载,因为它只是一个开发特性,但我的想法是,如果热重新加载不喜欢我的方法,那么我可能做得不正确,可能有更好的方法。

有什么想法?

我也很好奇,在生命周期中,什么时候是修改插槽节点的合适时机。此外,node.key是否是应用唯一密钥的正确位置?插槽节点中的哪个属性是要编辑的正确属性?(即,当在v-for循环中设置键时,在组件数据属性中也设置了' key‘)

非常感谢您能提供的任何见解!

代码语言:javascript
复制
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"
});
代码语言:javascript
复制
div {
 display: block;
 width: 100%;
}
代码语言:javascript
复制
<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>

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-07 02:42:46

尝试添加beforeUpdate挂钩:

代码语言:javascript
复制
  beforeUpdate() {
    this.$slots.default = this.$slots.default.map((node, index) => {
      node.key = `${node.tag}-${index}`
      return node
    })
  }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55028563

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档