5

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.

1 Answer 1

7

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>

2
  • I think that's exactly what I'm looking for, thank you. Accepting the answer when it allows me.
    – Sergi
    Commented Sep 11, 2019 at 10:08
  • you're welcome, look also to vuejs.org/v2/guide/transitions.html#List-Move-Transitions Commented Sep 11, 2019 at 10:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.