2

Consider the following sample and suggest proper way to handle this problem or clear my mind from this kind of thought

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 
}
4
  • this.a = this.b = false Commented Apr 26, 2017 at 6:39
  • I'm sorry. Consider a and b as different objects. Will update questions now! Commented Apr 26, 2017 at 6:41
  • 1
    vm.myData = {a: false, b: 6}, then make your data object have single data object inside it called myData. Commented Apr 26, 2017 at 6:43
  • this is awesome. But i need to use myData.a on all the reference instead of a. Commented Apr 26, 2017 at 6:46

1 Answer 1

6

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)
    },
}

See attached pen

Sign up to request clarification or add additional context in comments.

1 Comment

If you need IE11 support Object.assign will not work since that browser lacks the feature. You can use the Lodash polyfill for _.assign.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.