H
H
hryashik2022-02-04 22:36:08
Vue.js
hryashik, 2022-02-04 22:36:08

Vue. Why can't I change an array element in Data via a modod?

What is the task: clicking on an element should square its value.
We draw all the elements of the array, pass the element itself and its index. When clicked, the sqr function with the passed argument is triggered.

<li v-for="(item, index) in items" v-on:click="sqr(index)">
            {{item}}
        </li>

Actually a question to a method. Why doesn't it work?
sqr: function(index) {
         this.items[index] = Math.pow(this.items[index], 2);
      }

Why do you have to fence through the array splice?
sqr: function(index) {
         this.items.splice(index, 1, Math.pow(this.items[index], 2));
      }

Explain to a noob how it works. Is it about this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Samuel_Leonardo, 2022-02-04
@hryashik

Documentation in 9 languages, choose any
https://ru.vuejs.org/v2/guide/reactivity.html#%D0%...


Vue cannot track the following changes to an array:
Directly setting an item by index: vm.items[indexOfItem] = newValue
Explicitly changing an array's length: vm.items.length = newLength
For example:
var vm = new Vue({
  data: {
    items: ['a', 'b', 'c']
  }
})
vm.items[1] = 'x' // НЕ РЕАКТИВНО
vm.items.length = 2 // НЕ РЕАКТИВНО

There are two ways to solve the first problem, both will give the same effect as vm.items[indexOfItem] = newValue, plus trigger reactive app state updates:
// Использовать Vue.set
Vue.set(vm.items, indexOfItem, newValue)
// Использовать Array.prototype.splice
vm.items.splice(indexOfItem, 1, newValue)

You can use the vm.$set instance method, which is an alias for the global Vue.set: To solve the second problem, use splice :)
vm.$set(vm.items, indexOfItem, newValue)
vm.items.splice(newLength

A
Alexey Yarkov, 2022-02-04
@yarkov Vue.js

Why do you have to fence through the array splice?

Because it is necessary to read the documentation where it is written about this nuance.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question