Reputation: 29096
I would like to centralize my actions in models defined as follow:
class Foobar {
doit() {
console.log('I am doing it');
}
}
let foobar = new Foobar()
const app = new Vue({
store,
router,
foobar,
...
})
Later on, in a subcomponent, I would like to trigger an action on my model and I would like to do:
<template>
<b-button @click="doit">Do It</b-button>
</template>
<script>
export default {
methods: {
doit() {
this.$foobar.doit(); // <----
}
}
}
</script>
It seems $foobar
is not accessible down there.
What is the proper way in Vue to centralize actions in an external singleton?
Upvotes: 2
Views: 2507
Reputation: 1118
You could do it this way, but I'm not sure how well data will persist.
Vue.prototype.$foobar = foobar;
It might be better to use Vuex, so it is persisted through the app.
Inside the store:
const state = {
foobar: Foobar
}
const mutations = {
initialize (state) {
state.foobar = new Foobar();
}
}
Inside main/app.js:
store.commit('initialize')
Upvotes: 2