Search code examples
javascriptvue.jsvuex

Importing Vuex Plugins without defining a Store


so one of my store modules looks like this

export const state = () => ({
  posts: []
})

export const getters = {}

export const actions = {}

export const mutations = {
  fetchedPosts(state, posts) {
    state.posts = posts
    console.log("fetched")
  },

  pushPost(state, post) {
    state.posts.push(post)
    console.log("pushed")
  }
}

I want to use the vuex-persistedstate plugin but following their docs and the Vuex Plugin Docs https://vuex.vuejs.org/guide/plugins.html i didnt find a way to use the plugin inside my store, thanks in advance.


Solution

  • You just need to mention it once in your store/index.js:

    import Vue from 'vue'
    import Vuex from 'vuex'
    Vue.use(Vuex)
    import createPersistedState from 'vuex-persistedstate'
    import posts from '~/store/posts.store'
    
    ....
    
    export default new Vuex.Store({
      state:     { ... },
      mutations: { ... },
      actions: { ... }, 
      modules: { 
        posts,
        ... 
      },
      plugins: [createPersistedState()]
    })
    

    in your posts module:

    const state = () => ({ ... })
    const getters = { ... }
    const mutations = { ... }
    const actions = { ... }
    export default { namespaced: true, state, getters, actions, mutations }    
    

    that works for me.