0

In this fiddle : https://jsfiddle.net/djsuperfive/svctngeb/ I want to reverse the structure array in data when I click the button.
Why are the rendered list and the dump of structure not reactive whereas the console.log reflect that the reverse was effective ?

The code :

HTML

<div id="app">

  <draggable v-model="structure">
    <div v-for="(item, index) in structure" :style="'background-color:'+item.color">
      {{ item.title }}
    </div>
  </draggable>

  <button type="button" @click="reverse()">Reverse structure</button>

  <hr>
  <strong>dump structure:</strong>
  <pre>
    {{ structure }}
  </pre>
</div>

JS:

new Vue({
  el: '#app',
  data() {
    return {
      structure: [{
          title: 'Item A',
          color: '#ff0000'
        },
        {
          title: 'Item B',
          color: '#00ff00'
        },
        {
          title: 'Item C',
          color: '#0000ff'
        },
      ],
    }
  },
  methods: {
    reverse() {
      console.log(this.structure[0].title);
      _.reverse(this.structure);
      console.log(this.structure[0].title);
    }
  }
});

thanks

2 Answers 2

1

Max! Try to replace line:

_.reverse(this.structure);

with

this.structure.reverse();

I guess, Underscore.js does not have reverse method, because JavaScript has native one. Everything should work fine with native JS Array reverse function. Good luck!

Sign up to request clarification or add additional context in comments.

2 Comments

You're right Evgeny ! I also just found that it's working with the native reverse method.
Great to hear that!) Congratulations =)
0

The problem here seems to be that Vue does not detect that your array has changed: https://v2.vuejs.org/v2/guide/reactivity.html#Change-Detection-Caveats

The solution is to either replace this.structure with a new array or to have a reverse function that uses Vue.set().

this.structure = _.clone(_.reverse(this.structure));

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.