javascript - Vue - 在渲染之前修改插槽的正确方法 - 目标 : add transition group key programatically

标签 javascript vue.js

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

由于过渡组中的项目需要键控,我该如何将键添加到插槽项目中?由于它们被开槽而不是在 v-for 循环中呈现,我认为需要以编程方式添加键。

下面是一个可以玩的片段。您会在 created() Hook 中看到我的方法,它似乎适用于初始页面加载/呈现,但是当我的开发环境中的热重载刷新时, key 丢失并且有关过渡组子项需要 key 的错误又回来了.

是否有更好的方法来实现这一点,让热重载保持快乐?也许我不应该担心热重载,因为它只是一个开发功能,但我的想法是,如果热重载不喜欢我的方法,那么我可能做错了,可能有更好的方法。

想法?

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

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

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>

最佳答案

尝试添加 beforeUpdate 钩子(Hook):

  beforeUpdate() {
    this.$slots.default = this.$slots.default.map((node, index) => {
      node.key = `${node.tag}-${index}`
      return node
    })
  }

关于javascript - Vue - 在渲染之前修改插槽的正确方法 - 目标 : add transition group key programatically,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55028563/

相关文章:

javascript - "return false;"有什么作用?

javascript - 如何使用 JavaScript 将表单输入和音乐从一个页面传递到另一个页面?

javascript - 当我下降到使用 ng-repeat 创建的元素时如何向下滚动

node.js - 在 vuejs 中双重链接 2 个输入,并在中间进行计算

javascript - vuejs - 在函数调用时访问动态创建的输入

javascript - 变量没有被正确分配,可能的范围问题(在 getJSON() 中的 each() 中有一个开关的函数)

javascript - IE6 Javascript ClassName 改变显示

vue.js - 具有 nuxt-axios 和默认 header 插件的多个 API 提供程序

javascript - 为什么命名为 : false does not work for me

javascript - Vue JS "PROP MUTATING"用于上传图像