DEV Community

loading...

[VUE] How to access a variable from another instance

imrc21 profile image IMRC21 ・1 min read

Hi, I'm sorry if this might be a stupid question but I didn't find any answer on the web. Maybe because I am not using the correct keywords idk.
Anyway, I'm using VueJS to create an application that keeps track of your blood alcohol level.
I am using 3 vue instances and I have to access an array from a v-for witch is located in another vue instance.

Here is my code: https://jsfiddle.net/nsk0g1ou/

I've put my vue instance in a variable and tried to recall that but it's not working.

Should I use mixins?
I hope I've been clear.

Discussion (8)

pic
Editor guide
Collapse
martyhimmel profile image
Martin Himmel

If you're using multiple Vue instances, you can reference the instance data by instanceName.data.dataYouWant. Here's a quick example: jsfiddle.net/9uon0dwx/

Collapse
imrc21 profile image
IMRC21 Author

This works but I think I'll use the method adviced by fencina because I guess it's the best way.

Collapse
imrc21 profile image
IMRC21 Author

This is mind blowing, thank you so much.
I Will try.

Collapse
georgehanson profile image
George Hanson

Is there a reason you are using three different instances? Ideally, you should only be using one instance of Vue and then everything else is components.

Collapse
imrc21 profile image
IMRC21 Author

Thank you for your answer.
I am using more instances because Onsen UI (CSS framework) doesn't let me use one single vue instance.
Don't know why but if I use only one instance it does not show me anything.

Collapse
eladc profile image
Elad Cohen

Very strange.. can you show that in jsFiddle?
You should also check this repo (bit old): github.com/frandiox/onsenui-vue-ro...

Thread Thread
imrc21 profile image
IMRC21 Author

jsfiddle.net/ejm59tpo/1/

This is my code, on JsFiddle works the framework but not vue but I guess that's normal.
Also, my project is based on Cordova, I don't know if this could be related.

Thanks for that repo, however I'd like to keep the project simple.

Collapse
fencina profile image
fencina

Hi there!

You should try using a state pattern (check vuejs doc vuejs.org/v2/guide/state-managemen...)

Basically, you create a data object and allow your instances to "share" it.
Therefore, you can access and mutate this object from those instances, and it behaves in a reactive way.

If your application grow up, you should evaluate using vuex (vuex.vuejs.org/), which helps you with some issues you may find when working with state management, such as painful debugging.

Hope this helps you!