Vue.js,如何改变数组项的顺序并在DOM中同步更新?

5
在Vue实例中,我有一个名为“block”的数组,其中包含4个值。我使用v-for将此数组呈现到DOM中:
<div class="block" @click="shuffleArray()">
    <div v-for="(number, index) in block">
        <span :class="[`index--${index}`]">{{ number }}</span>
    </div>
</div>

这将创建一个带有4个 span 的 div,每个 span 都有一个类名为 "index--0"、"index--1" 等。
点击时,Array 的值会改变顺序:
shuffleArray: function() {
    const shifted = this.block.shift();
    this.block.push( shifted );
}

虽然值会发生变化,但它们不会在实际的DOM中移动,那么我如何实现当单击时,这些span实际上可以在DOM中改变位置呢?每个span都有一个应用于它的样式,因此我希望有一个视觉表示值确实改变了顺序:

    span.index--0 {
        background-color: tomato;
    }

    span.index--1 {
        background-color: khaki;
    }

    span.index--2 {
        background-color:lavenderblush;
    }

    span.index--3 {
        background-color: lightcoral;
    }

也许有一种仅使用CSS的解决方案,不需要DOM操作。
1个回答

7

我建议使用列表过渡来实现这种效果:

Vue.config.devtools = false;
Vue.config.productionTip = false;

new Vue({
  el: '#list-demo',
  data: {
    items: [1,2,3,4,5,6,7,8,9],
    nextNum: 10
  },
  methods: {
    randomIndex: function () {
      return Math.floor(Math.random() * this.items.length)
    },
    add: function () {
      this.items.splice(this.randomIndex(), 0, this.nextNum++)
    },
    remove: function () {
      this.items.splice(this.randomIndex(), 1)
    },
  }
})
.list-item {
  display: inline-block;
  margin-right: 10px;
}
.list-enter-active, .list-leave-active {
  transition: all 1s;
}
.list-enter, .list-leave-to /* .list-leave-active below version 2.1.8 */ {
  opacity: 0;
  transform: translateY(30px);
}
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>

<div id="list-demo">
  <button v-on:click="add">Add</button>
  <button v-on:click="remove">Remove</button>
  <transition-group name="list" tag="p">
    <span v-for="item in items" v-bind:key="item" class="list-item">
      {{ item }}
    </span>
  </transition-group>
</div>


我认为这正是我正在寻找的,谢谢。当它满足我的需求时,我会接受这个答案。 - Sergi
不用谢,还可以看一下vuejs.org/v2/guide/transitions.html#List-Move-Transitions。 - Boussadjra Brahim

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接