Vue.js 基于数组索引的数据转换

Vue.js Transition of data based on array index

在我的项目中,我必须使用数组来显示内容,并在单击时用数组的下一个条目更新它。

我不知道如何在我的数组索引更新时使用 vue.js Transition 标签制作动画。我希望内容消失,然后用新数据更改,然后出现新内容。可以用这个标签来做还是我必须自己做函数?

这是一个基本的例子。

<div @click="activeValue++">+1</div>

<transition mode="out-in" name="fade">
    <div>{{myArray[activeValue].title}}</div>
</transition>
data() {
        return {
            activeValue: 0,
            myArray: [
                {
                    title: "Title 1",
                    content: "Lorem impsum",
                },
                {
                    title: "Title 2",
                    content: "Lorem impsum",
                },
                {
                    title: "Title 3",
                    content: "Lorem impsum",
                },
            ]
        }
    },

// Basic vue.js transition
.fade-enter-active, .fade-leave-active {
  transition: opacity .5s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
  opacity: 0;
}

引用Vue Documentation

Vue provides a transition wrapper component, allowing you to add entering/leaving transitions for any element or component in the following contexts:

  • Conditional rendering (using v-if)
  • Conditional display (using v-show)
  • Dynamic components
  • Component root nodes

也就是说,Transition 标签需要 DOM 元素有条件地成为 rendered/unrendered,以便让过渡发生。这是一个 CodeSandbox sample 你可以试试看。

在 div 中添加 key 将有助于转换以区分当 activeValue 更改时 div 中的不同

<div :key="activeValue">
   {{ myArray[activeValue].title }}
</div>

这里是codesandbox供大家参考:

https://codesandbox.io/s/crazy-dubinsky-ruztq?file=/src/components/HelloWorld.vue

P.S。请处理大于 2 的 activeValue++(这意味着超过 3 项