css3 转换不适用于 vue2 中的 v-for

时间:2021-04-04 10:17:58

标签: css vue.js

我在vue2中使用transtion。我在 css 中添加了过渡。 Vue 模板显示两个框。一种方法是使用 v-for 和数组,另一种方法是使用变量。 btn2 有效但 btn1 无效。

<style lang="sass">
    .item
        width: 120px
        height: 120px
        background-color: bisque
        transition: margin-left 500ms
</style>
<template>
    <div>
        <div class="item" v-for="item in list" :key="item.index" :style="{marginLeft: item.index + 'px'}">{{ item.value }}</div>
        <div class="item" :style="{marginLeft: left + 'px'}">123</div>
        <button @click="addone">btn1</button>
        <button @click="addtwo">btn2</button>
    </div>
</template>
<script>
    export default {
        name: 'Heap',
        data() {
            return {
                left: 100,
                list: [
                    {
                        value: 12,
                        index: 10
                    }
                ]
            }
        },
        methods: {
            addone() {
                this.list[0]['index']+=10
            },
            addtwo() {
                this.left+=10
            }
        }
    }
</script>

1 个答案:

答案 0 :(得分:1)

您在第一个 div 上使用了代码 :key="item.index"。然后您的代码会更新相同的索引。

当一个键的值发生变化时,它所附加的组件会重新渲染。您没有看到动画发生,因为您不是动态增加 CSS,而是使用新 CSS 重新渲染元素。

key 的目的是帮助 Vue 跟踪列表中给定节点的身份。它让 Vue 知道它可以保留和修补哪些节点,哪些需要再次渲染。

您应该尽可能使用静态的、不变的值作为键。在以下示例中,我向您的对象添加了一个 id 属性并将其用作键。

<style lang="sass">
.item
  width: 120px
  height: 120px
  background-color: bisque
  transition: margin-left 500ms
</style>
<template>
  <div>
    <div
      v-for="item in list"
      :key="item.id"
      class="item"
      :style="{marginLeft: item.index.toString() + 'px'}"
    >
      {{ item.value }}
    </div>
    <div class="item" :style="{marginLeft: left.toString() + 'px'}">123</div>
    <button @click="addone">btn1</button>
    <button @click="addtwo">btn2</button>
  </div>
</template>
<script>
export default {
  name: 'Example',
  data() {
    return {
      left: 100,
      list: [
        {
          id: '1',
          value: 12,
          index: 10,
        },
      ],
    };
  },
  methods: {
    addone() {
      this.list[0].index += 10;
    },
    addtwo() {
      this.left += 10;
    },
  },
};
</script>