Use vuex in vue3+vite

Foreword:

      When using vuex in the project created by vue3+vite, it should be noted that part of vite is different from the previous webpack. For example, it does not support require. When you want to directly upgrade the vue2 project to vue3, you need to change a lot of places , if you have to use vite, remember to change the relevant content.

Specific steps:

1. Install vuex (vue3 recommends 4.0+)

pnpm i vuex -S

2. Configuration in main.js

import store from '@/store'

// hx-app的全局配置
const app = createApp(App)

app.use(store)

3. Create new related folders and files, configure multiple js inside different vuex, use vuex modules to put different pages and files, and then use one getters.js uniformly

index.js core file, import.meta.glob  is used here instead of require

import getters from './getters'
import { createStore } from 'vuex'

const modulesFiles = import.meta.glob('./modules/*.js',{ eager: true }); // 异步方式

let modules = {}
for (const [key, value] of Object.entries(modulesFiles)) {
  var moduleName = key.replace(/^\.\/(.*)\.\w+$/, '$1');
  const name = moduleName.split('/')[1]
  modules[name] = value.default
}

const store = createStore({
  modules,
  getters
})

export default store

Getters.js internally sends different state data according to different pages

const getters = {
  sidebar: state => state.app.sidebar,
  token: state => state.user.token,
}

export default getters

app.js can define different variables, and then unify export default

const state = {
  sidebar: '123'
}

const mutations = {
  TOGGLE_SIDEBAR: state => {
    state.sidebar = '2222'
   
  },

const actions = {
  toggleSideBar({ commit }) {
    commit('TOGGLE_SIDEBAR')
  }
}

export default {
  namespaced: true,// 为每个模块添加一个前缀名,保证模块命明不冲突
  state,
  mutations,
  actions
}

user.js can also return an object directly, any way of writing is acceptable

export default {
  state: {
    token: '123'
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
  },

  actions: {
  }
}

4. Specific page use

1) import

import { useStore } from 'vuex'

2) specific use

setup(){
    const store = useStore()
}

3) Use the method in mutations

store.commit("app/TOGGLE_SIDEBAR", 1)

4) Use the method in actions

store.dispatch("app/asyncAddStoreCount", 2)

5. A plug-in (vuex-persistedstate) is launched in vuex, which can solve the problem of refreshing data without saving,

In addition to vuex, data can be stored locally and in sessions (both supported)

1) install

pnpm i vuex-persistedstate -S

2)store/index.js

import createPersistedstate from 'vuex-persistedstate' //第一步导入
import { createStore } from 'vuex'


const store = createStore({
  modules,
  getters,
  //第二步是加这段代码,默认是存到了localStorage中
  plugins: [
    createPersistedstate({
      key: 'vuex-local', //存储持久状态的键。(默认:vuex)
      paths: ['user'], //部分持续状态的任何路径的数组。如果不加,默认所有。
      // storage: window.sessionStorage //默认存储到localStorage,想要存储到sessionStorage
    })
  ]
})

API

createPersistedState([options]) creates a new instance of the plugin with the given options. The following options can be provided to configure the plugin to your specific needs:

  • key : The key to store the persistent state. (default: vuex)
  • paths : An array of any paths that partially persist state. If no path is given, the full state is persistent. (default:[])
  • reducer : A function that will be called to persist state based on the given path. These values ​​are included by default.
  • subscriber : A function that is called to set up a mutation subscription. The default is store => handler => store.subscribe(handler)
  • storage : instead of (or with) getState and setState. The default is localStorage.
  • getState : The function that will be called to rehydrate the previous persistent state. Storage is used by default.
  • setState : The function that will be called to persist the given state. Storage is used by default.
  • filter : The function that will be called to filter any mutations that will eventually trigger setState to store. default() => true

Guess you like

Origin blog.csdn.net/qq_41619796/article/details/128019551