Mikee
Mikee

Reputation: 1661

How to reference a Vue data property from another data property

I'm learning Vue.JS and all my attempts to reference the dashboards property from the currentDashboard data expression result in 'dashboards is not defined'. Is Vue somehow evaluating the currentDashboard expression prior to dashboards or do I need some qualifier to reference it, this does not help?

vue = new Vue({
el: '#dashboard',
data: {
    dashboards: store.getDashboards(),
    currentDashboard: dashboards[0],
}

})

Upvotes: 7

Views: 11182

Answers (2)

JP. Aulet
JP. Aulet

Reputation: 4418

I think that one solution is that you could use the computed method for it, because dashboards[0] are not defined in the same created cycle. Try with something like:

data: {
    dashboards: store.getDashboards(),
},
computed: {
  currentDashboard: function () { return this.dashboards[0] }
}

This way the variable is defined when you make the currentDashboard call and you don't have to refactor the Vue.js call for this var.

Edit: Yes, if you want to know why, as points Joel, in the official documentation you can read:

If you know you’ll need a property later, but it starts out empty or non-existent, you’ll need to set some initial value.

In this case, the data() method starts with all the values in a queue, without assigning it, and for this, the starting value is undefined. Here: https://v2.vuejs.org/v2/guide/instance.html

Hope it helps!

Upvotes: 7

Ramesh Maharjan
Ramesh Maharjan

Reputation: 41987

you can create dashboard variable before you return data properties so that you can use it multiple times in data properties.

vue = new Vue({
el: '#dashboard',
data() {
    let dashboard = store.getDashboards()
    dashboards: dashboard,
    currentDashboard: dashboard[0],
}

I hope this is helpful

Upvotes: 2

Related Questions