Answer the question
In order to leave comments, you need to log in
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>
sqr: function(index) {
this.items[index] = Math.pow(this.items[index], 2);
}
sqr: function(index) {
this.items.splice(index, 1, Math.pow(this.items[index], 2));
}
Answer the question
In order to leave comments, you need to log in
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
Why do you have to fence through the array splice?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question