Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access Vuex from Vue Plugin?

Tags:

vuejs2

vuex

How can I access my store from my plugin? Console returns undefined.

import store from './store';

export default {
    install(vue, opts){
        Vue.myGlobalFunction = function(){
            console.log(store);
        }
    }
}
like image 766
Stephane Avatar asked Oct 31 '18 17:10

Stephane


People also ask

Is Vuex a plugin?

A Vuex plugin is simply a function that receives the store as the only argument: const myPlugin = (store) => { // called when the store is initialized store. subscribe((mutation, state) => { // called after every mutation. // The mutation comes in the format of `{ type, payload }`. }) }

Does Vuex work with Vue 3?

The short answer is: Yes. Vuex is the preferred state management solution for Vue apps, and Vuex 4 is the version compatible with Vue 3. Do take note, however, that using Vuex for state management depends on the complexity of your application.

Is Vuex part of Vue?

Vuex is a state management pattern + library for Vue.js applications. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion.


1 Answers

I recently had to do this too to make a pouchDb plugin, and came up with a new way.

When you create your first Vue object, you can do this.

import PouchDb from '@/pouch_db/PouchDbPlugin'

let DefaultVue = Vue.extend({
  components: {App},
  store,
  created () {
    Vue.use(PouchDb, this.$store) // Create it by passing in the store you want to use
  }
})

My plugin adds an additional store, and it's own mutations and getters.

export default {
  install (Vue, store) {
    store.registerModule('PouchDb', pds)
    const pouchDb = new PouchDb(store)
    Vue.pouchDb = pouchDb
    Vue.prototype.$pouchDb = pouchDb
  }
}

Inside the constructor, I store the store

class PouchDb {
  constructor (store) {
    this.store = store
    // ... etc.
  }
  // ... more functions
}

And then use it in other functions

class PouchDb {
    // ... constructor and other functions
    async addSync (docId) {
       this.store.dispatch('PouchDb/addSync', docId)
    }
}

It's a bit of a cheat to pass in the store, but seems to work nicely. It's usable throughout the app like this

// Inside vuex store
Vue.pouchDb.addSync(// ...etc)

// inside component
this.$pouchDb.removeSync(// ...etc)
like image 63
Trevor Avatar answered Sep 21 '22 13:09

Trevor