Problems encountered in the vue project

(1) When the data dynamically bound by v-model is nested multi-layer example: [{},{}] This is not responsive

Solution: $set , $set was born to solve the failure of two-way binding (as long as the address of the data has not changed, Vue cannot detect data changes)

this.$set(original array, index value, value to be assigned)

this.$set(original object, attribute, value to be assigned)

 <template>

      <p v-for="item in errors" :key="item.id">{ {item.message}}</p>

     <el-button  @click="errorClick">更改</el-button>

</template>

 

export default {

  data () {

    return {   

        errors:[

           { message: "one", id: "1" },

           { message: "two", id: "2" },

           { message: "three", id: "3" }

       ]

    }

  }

}

 methods: {

        errorClick(val){

            // this.errors[0] = {message:'11',id:0} // value changed but view not updated

            // console.log('this.errors',this.errors[0]);  // {message:'11',id:0}

            // 1. Change the array

            this.$set(this.errors,0,{message:'11',id:0})

            // 2. Change the object

            this.$set(this.errors[0],'message','four')

         }

}

Extension: Several situations where two-way binding fails

1. When you use the index to directly set an array item, for example: vm.items[indexOfItem] = newValue
2. When you modify the length of the array, for example: vm.items.length = newLength
3. Due to the limitation of JavaScript, Vue Cannot detect addition or removal of object properties

Guess you like

Origin blog.csdn.net/m0_63304840/article/details/129277501