How to access a Vuejs data property from another data property?

Viewed 1821

These are my code

data: {
     cat1 : {name: "Category 1", reference : false},
     cat2 : {name: "Subcategory 2", reference: this.cat1}
}

When I am going to called this.cat2.reference from any function, its giving me value false. I don't want to declare the cat1 outside somewhere and make reference here. I want the exactly same structure as above so that, I can get the cat2 reference perfectly.

Anyone could you please advice me any solution?

3 Answers

One option would be to create your data object with some getter methods

For example

new Vue({
  el: '#newUser',
  data: () => { // make sure to use a "data" function
    // initialise with a declared variable
    const formData = {
      cat1, // not sure where these come from
      cat2,
      cat3,
      cat5: { name: 'Subcategory 5', get reference() { return formData.cat1 }}
    }
    return { formData }
  }
}

Demo ~ https://jsfiddle.net/ztfgapxh/

I think you'll be better using a computed property:

data: {
  cat1 : {name: "Category 1", reference : false}
}
computed: {
  cat2() {
    return {name: "Subcategory 2", reference: this.cat1}
  }
}

Now you can call this.cat1 and this.cat2 but cat2 will be updated every time cat1 changes.

https://v2.vuejs.org/v2/guide/computed.html

EDIT: if you want to handle all catX in a consistent way, you can have all of them to be computed properties

You can set the reference as a function that will return this.data.cat1 :

data: {
     cat1 : {name: "Category 1", reference : ()=> {return null;}},
     cat2 : {name: "Subcategory 2", reference: ()=> {return this.data.cat1;}}
}

In order to get the reference of the cat2 you'll need to call it as a function :

var referenceOfCat2 = this.data.cat2.reference();
//referenceOfCat2 = {name: "Category 1", reference : ()=> {return null}}

Although if you try to call this function outside the component itself, it won't work. If you want to pass cat2 to another component, you'll need to set his reference (call the ref function ) before passing it, otherwise once it reaches the other component, the data target won't be the same (unless some tweaks) and the reference() won't work

Related