VueJS How to access Mounted() variables in Methods
I will first suggest you to stop using var, and use the latest, let and const to declare variable
You have to first declare a variable in
data(){ return { allcards: "", mixer: "" }}
and then in your mounted()
mounted() { this.allcards = this.$refs.allcards; this.mixer = mixitup(this.allcards); },methods: { getCatval() { let category = event.target.value; this.mixer } }
like Ninth Autumn said : object returned by the data
function and props
of your components are defined as attributes of the component, like your methods defined in the method
attribute of a component, it's in this
so you can use it everywhere in your component !
Here an example:
data() { return { yourVar: 'hello', }; }, mounted() { this.sayHello(); }, method: { sayHello() { console.log(this.yourVar); }, },
Upate
you cannot pass any value outside if it's in block scope - Either you need to get it from a common place or set any common value
As I can see, var mixer = mixitup(allcards);
is in the end acting as a function
which does some operation with allcards
passed to it and then returns a value.
1 - Place it to different helper
file if mixitup
is totally independent and not using any vue
props used by your component
In your helper.js
const mixitup = cards => { // Do some operation with cards let modifiedCards = 'Hey I get returned by your function' return modifiedCards}export default { mixitup}
And then in your vue
file just import
it and use it is as a method
.
In yourVue.vue
import Helpers from '...path../helpers' const mixitup = Helpers.mixitup export default { name: 'YourVue', data: ..., computed: ..., mounted() { const mixer = mixitup(allcards) }, methods: { mixitup, // this will make it as `vue` method and accessible through this getCatval() { var category = event.target.value; this.mixitup(allcards) } } }
2- Use it as mixins
if your mixitup
dependent to your vue
and have access to vue
properties
In your yourVueMixins.js
:
export default { methods: { mixitup(cards) { // Do some operation with cards let modifiedCards = 'Hey I get returned by your function' return modifiedCards } }}
And import
it in your vue
file:
import YourVueMixins from '...mixins../YourVueMixins' const mixitup = Helpers.mixitup export default { name: 'YourVue', mixins: [YourVueMixins] // this will have that function as vue property data: ..., computed: ..., mounted() { const mixer = this.mixitup(allcards) }, methods: { getCatval() { var category = event.target.value; this.mixitup(allcards) } } }