How to reference a Vue data property from another data property


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



})




1 Answer
1



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:


computed


dashboards[0]


created


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.


currentDashboard



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://vuejs.org/v2/guide/instance.html


undefined



Hope it helps!





Thanks, that is actually what I ended up doing to get things working as I am learning. However this is really not a computed value it's just a reference and I would like to know why I can't seem to do this?
– Mikee
Jul 2 at 19:33





This is because when the data object is created it needs to know all the values upfront, you can't construct a property based on another property since the base object hasn't been created yet. If you had calculated store.getDashboards() prior the new Vue instance, then you could have referenced it.
– Joel Lucsy
Jul 2 at 20:12






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

JMeter fails on beanshell imports

Why in node-red my HTTP POST no receive payload from inject?

PHP contact form sending but not receiving emails