DEV Community

Roland Csibrei
Roland Csibrei

Posted on

Add new VUE reactive property to an object

Hey guys!
Just a quick hint on VUE reactive properties.

If you want a new property of an object to be reactive, do it this way.

Bad:

const vueObj = {}
vueObj.newProperty = {}

Good:

const vueObj = {}
Vue.set(vueObj, 'newProperty', {})`

For example you may have a button, which adds a new empty object, like this:

<template>
  <my-field-editor v-model="field" v-id="showEdit" />
</template>

Bad:

 methods: {
    addField () {
      this.field = {}
      this.field.id = uuidv4()
      this.field.required = false
      this.field.name = ''

      this.showEdit = true

    },

Good:

 methods: {
    addField () {
      this.field = {}
      Vue.set(field, 'id', uuidv4())
      Vue.set(field, 'required', false)
      Vue.set(field, 'name',  '')

      this.showEdit = true
    },

Top comments (0)