首页 > 解决方案 > Vue.js,更改数组项的顺序并在 DOM 中进行更改

问题描述

在 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 个跨度的 div,每个跨度都有一个类“index--0”、“index--1”等。

单击时,Array 的值更改顺序:

shuffleArray: function() {
    const shifted = this.block.shift();
    this.block.push( shifted );
}

虽然值确实发生了变化,但它们并没有在实际的 DOM 中移动,我怎样才能在单击时实现这一点,跨度实际上会在 DOM 中改变位置?每个跨度都应用了一个样式,所以我想要一个值确实改变顺序的视觉表示:

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

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

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

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

也许有一个不需要 DOM 操作的纯 CSS 解决方案。

标签: javascriptcssvue.jsvuejs2vue-component

解决方案


我建议使用list tranisition它来制作这样的花哨:

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>


推荐阅读