【问题标题】:Vue multimensional list transition on reorder重新排序时的Vue多维列表转换
【发布时间】:2020-08-02 03:49:10
【问题描述】:

我正在尝试获得一个项目列表/网格,以在关于列表转换的 Vue dcs 中看到具有奇特效果的转换,我将当前代码基于此处给出的示例:

https://codesandbox.io/s/github/vuejs/vuejs.org/tree/master/src/v2/examples/vue-20-list-move-transitions?file=/index.html:517-574

来自关于 Vue 转换的官方文档。

https://vuejs.org/v2/guide/transitions.html#List-Move-Transitions

我的代码:

<template>
  <div class="main_container" @click="shuffle()">
    <transition-group name="cell" tag="div" class="container">
      <div class="cell" v-border v-for="(item, index) in items" :key="index">{{ item.n }}</div>
    </transition-group>
  </div>
</template>
<!--SCRIPTS-->
<script>
export default {
  name: "LAYOUTcard19",

  data() {
    return {
      items: [],
    };
  },

  mounted() {
    for (let i = 0; i < 20; i++) {
      let random = Math.random().toFixed(2);
      let cell = { n: random };
      this.items.push(cell);
    }
  },

  methods: {
    shuffle() {
      console.log("shuffle");
      this.items = _.shuffle(this.items);
    },
  },
};
</script>
<!--STYLES-->
<style scoped>
.main_container {
  width: 400px;
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.container {
  width: 300px;
  height: 300px;
  display: flex;
  flex-wrap: wrap;
}
.cell {
  width: 20%;
  height: 20%;
  display: flex;
}
.cell-move {
  transition: transform 1s;
}
</style>

【问题讨论】:

  • 有什么问题?
  • 当我随机播放单元格时不动画
  • 为您的代码创建一个工作示例来展示问题

标签: javascript vue.js


【解决方案1】:

来自Vue documentation on transition-groups

里面的元素总是需要有唯一的key属性。

因此,当您将索引分配为 v-for 循环的 key 时,您会收到一条非常直接的警告:

(Emitted value instead of an instance of Error) Do not use v-for index as key on <transition-group> children, this is the same as not using keys.

要纠正错误行为,请在生成期间为您的项目添加一个唯一 ID:

mounted() {
  for (let i = 0; i < 20; i++) {
    let random = Math.random().toFixed(2);
    let cell = {id: i, n: random }; // here we add the id
    this.items.push(cell);
  }
}

当使用v-for时,该id可以用作key

<div class="cell" v-border v-for="(item) in items" :key="item.id">{{ item.n }}</div>

【讨论】:

    猜你喜欢
    • 2012-08-11
    • 1970-01-01
    • 2019-08-02
    • 1970-01-01
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-06
    相关资源
    最近更新 更多