Sergi
Sergi

Reputation: 1240

Vue.js, change the Array items order and make that change in the DOM as well

In a Vue instance, I have an Array with the name of "block" that holds 4 values. I render this Array to the DOM with a v-for:

<div class="block" @click="shuffleArray()">
    <div v-for="(number, index) in block">
        <span :class="[`index--${index}`]">{{ number }}</span>
    </div>
</div>

this creates a div with 4 spans inside, each of which has a class of "index--0", "index--1", etc.

When clicked, the values of the Array change order:

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

While the values do change, they don't move in the actual DOM, how can I achieve that when clicked, the spans actually change place in the DOM? Each span has a style applied to it so I would like a visual representation that the values do change order:

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

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

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

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

Maybe there is a CSS only solution that does not require DOM manipulation.

Upvotes: 5

Views: 1575

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

I recommend to use list tranisition in order to make that fancy like :

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>

Upvotes: 7

Related Questions