考虑以下示例并提出处理此问题的正确方法或清除我的思想中的这种想法
data(){
return{
a: true,
b: 5
}
},
someMethod: function(){
/*Currently update using the following lines,
this.a = false
this.b = 6
*/
//Is there anything to update multiple attributes at a single line
//Like in ReactJS
//this.setState({})
//Or correct my VueJS knowledge if im wrong
}
Run Code Online (Sandbox Code Playgroud)
You can sort of do what you're asking with Object.assign(...)
. It offers the shallow merge as in this.setState
, and you can set base level properties this way
Vue also has vm.$set(this, propName, value)
and Vue.set(this, propName, value)
, although these offer similar functionality, they don't merge existing props with the new ones (they simply override), and they don't allow you set base level properties using the same syntax as this.setState({})
but would require you to use Vue.set(this, propName, {})
// Poor mans setState(...), only using the shallow merge
methods: {
setState(obj) {
Object.assign(this, obj)
},
}
Run Code Online (Sandbox Code Playgroud)