vue, the data object is how to add a new property? (Nima This interview questions actually asked me to run into ....)

What happens when the property Vue add a new attribute to the data of the object, how to solve?

Example:

<template>
<div> <ul> <li v-for="value in obj" :key="value"> {{value}} </li> </ul> <button @click="addObjB">添加obj.b</button> </div> </template> <script> export default{ data () { return { obj: { a: 'obj.a' } } }, methods: { addObjB () { this.obj.b = 'obj.b' console.log(this.obj) } } } </script> <style></style> 

Click the button will find, obj.b has been successfully added, but the view did not refresh:

 

 
The reason is that when the Vue instance is created, obj.b not declared, and therefore have not been converted into Vue responsive property, naturally, does not trigger update view, then you need to use Vue global api-- $ set ( ):
addObjB () {    
// this.obj.b = 'obj.b' this.$set(this.obj, 'b', 'obj.b') console.log(this.obj) } 

$ SET () method is equivalent to manually handle the obj.b responsive to a property, then the view will also change:

 

Guess you like

Origin www.cnblogs.com/fxwoniu/p/11645980.html