181219 how mpvue achieves the effect of native storage through vuex

Two ways of using vuex in mpvue

Troublesome Edition

  1. Create the store.js file in the src directory
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
  state: {
    str: 'in store',
    num: 521
  }
})
export default store
  1. Import the index.vue file of the page
import store from '../../store'
  1. Page usage
store.state.str

Easy edition

The above is a brief introduction of how to use vuex in vue. But there is a problem in this. When we have countless pages that need to use store, you need to refer to it countless times, and the above methods can't access store in the subcomponent. So there's the next easy version.
Make the following adjustments in main.js of the root directory

import Vue from 'vue'
import App from './index'
// Introducing store
import store from '../../store'
//Vue mount store
Vue.prototype.$store = store
const app = new Vue(App)
app.$mount()

Use:

this.$store.state.str

Movement modify state

Add the store file after the movement

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
  state: {
    str: 'hello world',
    num: 521
  },
  mutations: {
    changeStr (state, value) {
      state.str = value
    }
  }
})
export default store

Modified in vue file

mounted () {
    console.log('Is there any difference')
    console.log(this.$store.state.str)
    this.$store.commit('changeStr', '88 world')
    console.log(this.$store.state.str)
  }

This can prove that we can use commit to modify the store file on the page every time, but it is not persistent, so how can we achieve persistence in the applet?

Persistence of vuex persistent state

The store.js file is modified as follows

import Vue from 'vue'
import Vuex from 'vuex'
// Introducing persistence plug-ins
import createPersistedState from 'vuex-persistedstate'
Vue.use(Vuex)
const store = new Vuex.Store({
  state: {
    str: 'hello world',
    num: 521
  },
  mutations: {
    changeStr (state, value) {
      state.str = value
    }
  },
  plugins: [
    createPersistedState({
      storage: {
        getItem: key => wx.getStorageSync(key),
        setItem: (key, value) => wx.setStorageSync(key, value),
        // removeItem: key => wx.clearStorageSync(key)
        removeItem: key => () => {}
      }
    })
  ]
})
export default store

The above practice is feasible.

Keywords: Vue

Added by matty on Thu, 05 Dec 2019 04:17:42 +0200