【问题标题】:Vue.js, change the Array items order and make that change in the DOM as wellVue.js,更改数组项的顺序并在 DOM 中进行更改
【发布时间】:2020-01-13 03:31:58
【问题描述】:

在 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”等。

点击后,数组的值改变顺序:

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 解决方案。

【问题讨论】:

    标签: javascript css vue.js vuejs2 vue-component


    【解决方案1】:

    我建议使用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>

    【讨论】:

    • 我想这正是我想要的,谢谢。在允许的情况下接受答案。
    • 不客气,也请查看 vuejs.org/v2/guide/transitions.html#List-Move-Transitions
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多