Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference a Vue data property from another data property

Tags:

vue.js

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

})

like image 864
Mikee Avatar asked Jul 02 '18 18:07

Mikee


People also ask

Are Props passed by reference Vue?

Vue does not take a copy when you pass objects via props. If you pass an object via a prop then both components will be seeing the same object. As it's the same object, any property changes made by the child will also impact the other parent.

What does data () do in Vue?

data # A function that returns the initial reactive state for the component instance. The function is expected to return a plain JavaScript object, which will be made reactive by Vue.

How do I transfer data from components to Vue?

Using Props To Share Data From Parent To Child # VueJS props are the simplest way to share data between components. Props are custom attributes that we can give to a component. Then, in our template, we can give those attributes values and — BAM — we're passing data from a parent to a child component!


2 Answers

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!

like image 127
JP. Aulet Avatar answered Oct 20 '22 00:10

JP. Aulet


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

like image 33
Ramesh Maharjan Avatar answered Oct 20 '22 00:10

Ramesh Maharjan