T
T
tehnazavr2018-02-17 09:54:09
JavaScript
tehnazavr, 2018-02-17 09:54:09

How to work with plugins in Vuex?

I can't really understand how to work with vuex plugins. Not very much info. Actually, I have a task so that a certain state is not reset to zero when the page is reloaded. I decided to use vuex-persistedstate for this.
The docs provide an example of using the plugin. How to tell the plugin what specific state to synchronize? And is it possible to tell him from some action that now you need to overwrite / delete something from localstorage?

const store = new Store({
  // ...
  plugins: [
    createPersistedState({
      storage: {
        getItem: key => Cookies.get(key),
        setItem: (key, value) => Cookies.set(key, value, { expires: 3, secure: true }),
        removeItem: key => Cookies.remove(key)
      }
    })
  ]
})

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-02-17
@tehnazavr

How to tell the plugin what specific state to synchronize?

With vuex-persistedstate, when creating an instance, you can define the paths property in the settings, which lists which parts of the state should be saved.
Or you can define a reducer method that takes the current state and returns the state to save.
Nothing like this is needed, localStorage is updated automatically when the state is updated.
Or do you want the state to be saved only at certain moments? Then the filter method will help you - it gets an object containing the name of the mutation being performed (yes, the mutation, not the action) and its payload, returns true / false - it is necessary / not necessary to save.
const store = new Store({
  // ...
  plugins: [
    createPersistedState({
      storage: {
        getItem: key => Cookies.get(key),
        setItem: (key, value) => Cookies.set(key, value, { expires: 3, secure: true }),
        removeItem: key => Cookies.remove(key)
      }
    })
  ]
})

This is an example of storage customization from the plugin description, I don’t think you need it - you are going to use localStorage, it is the default storage.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question