V-for loops are no longer data driven

problem description

v-for loop is not data driven

the environmental background of the problems and what methods you have tried

do a little exercise for the scaffolding you just created

related codes

/ / Please paste the code text below (do not replace the code with pictures)
< template >
< div id= "app" >

<ul>
  <li v-for="(item,index) in arrB" :key="index" :class="{act: item}" @click="touch(index)">{{item}}</li>
</ul>

< / div >
< / template >

< script >

export default {
name: "app",
data () {

return{
  arrB: [false, false, false, false, true]
}

},
methods: {

touch(item){
  let value = this.arrB[item]
  if (value) {
    this.arrB[item] = false
  } else {
    this.arrB[item] = true
  }
  console.log(this.arrB)
}

}
}
< / script >

< style lang= "scss" >
* {
margin: 0;
padding: 0;
}
ul {
list-style: none;
display: flex;
border: 1px solid-sharpccc;
border-right: 0;
margin: 20px;
li {

flex: 1;
height: 50px;
line-height: 50px;
text-align: center;
border-right: 1px solid -sharpccc;

}
.act {

background: red;

}
}
< / style >

what result do you expect? What is the error message actually seen?

true turns red and false is white

Nov.04,2021

cannot directly manipulate array substitution and modify values in VUE, because ES6 does not support listening for changes in array data, so you can only use Vue modified array mutation method array.push (), array.unshift (), array.splice () and other methods to modify array data. There is also a vue.set () that can be used to modify array changes. Through these methods to modify the data of vue, you will listen for changes, and the view will change accordingly.


    The main problem with
  1. is that Vue does not detect array changes.
  2. prerequisites for Vue to monitor array changes:

    • replace array (pointer to other array).
    • use the array variation method.
    • uses set to assign values to array items.

so part of the code analysis for processing the array.

  1. if the aim is to modify the array using the mutation method, you need to make sure that the ide/list.html-sharp%E5%8F%98%E5%BC%82%E6%96%B9%E6%B3%95" rel=" nofollow noreferrer "> mutation method is used
  2. if the purpose is to replace the array, make sure that the replaced array is the same object as the original array, and make sure that it is replace , not repeat assignment .
  3. if you want to set an item directly using the index, you cannot modify the value directly. Instead, you need to cooperate with the set method provided by Vue to ide/list.html-sharp%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A1%B9" rel=" nofollow noreferrer "> modify .
The problem with the

subject is the third point, which requires the use of set to directly modify the value of the array item.

Menu