Vue3基础之Vuex使用和持久化存储

简述

我们本章节主要是通过两种方式使用Vuex,第一种是简单使用,适用于简单业务不特别依赖与vuex。第二种是模块化,适用于复杂的业务处理,按模块化区分。持久化存储,因部分关键数据在页面刷新后还需要保存,所以需要持久化存储。
Vue3使用vuex,其实和Vue2使用一样。

Vue2使用Vuex之Vue使用vuex进行项目模块化,两种调用方式

安装

  • 安装vuex
npm install vuex -s
  • 安装vue-persistedstate
npm i vuex-persistedstate -s

目录

一. 基本使用
二. 模块化使用
三. 持久化存储

一.基本使用

  1. 项目结构


    4.png
  2. Main.js配置
import { createApp } from 'vue' 
import App from './App.vue'
import store from './stores/index'

const app = createApp(App);
 
app.use(store); // 挂载Vuex
app.mount('#app'); 
  1. Vuex的index.js
import {createStore} from 'vuex'
 const store = new createStore({
    state: { 
        acount:'账号是123456'
    }, 
    getters:{
        getAcount(state){
           return state.acount
        }
    },
    actions: {
        actAcount(state,msg){
            state.commit('setAcount',msg)
        }
    },
    mutations: {
       setAcount(state,msg){
        state.acount = msg
       }
    }, 
})
export default store
  1. 使用vuex
  • 使用computed,实现数据双向绑定,否则数据不会变化
  • vue3中使用,主要是拿到useStore 既可调用了。
<template>
 <div> 
    <div class="div1">
        vue3使用vuex
         <div>获取 state内数据: {{acount}}</div>
         <div>获取 getters内数据: {{getAcount}}</div>
         <button @click="clickActions"> 调用actions内函数:设置acount</button>
         <button @click="clickMutations"> 调用mutations内函数:设置acount</button>
    </div> 
 </div>
</template>
<script setup>
import {computed} from 'vue'
import { useStore } from 'vuex';
 const store = new useStore();
 const acount =  computed(()=>{
      return store.state.acount
 })
 const getAcount =computed(()=>{return store.getters.getAcount}) 
 const clickActions = ()=>{
    store.dispatch('actAcount','11111111111111')
 }
 const clickMutations = ()=>{
    store.commit('setAcount','22222222222222222')
 }

 console.log(store);
</script>

二.模块化使用

  1. 项目结构


    5.png
  2. Main.js配置

import { createApp } from 'vue' 
import App from './App.vue'
import store from './stores/index'

const app = createApp(App);
 
app.use(store); // 挂载Vuex
app.mount('#app'); 
  1. Vuex的index.js

import {createStore} from 'vuex'

import userInfo from './modules/user/info.js'

 const store = new createStore({ 
    modules: {
        //数据模块化
        userInfo: userInfo
    }
})
export default store
  1. modules下面的user模块
const state = {
  name: '简书'
}

const getters = {
    getName(state){
        return state.name
    }
}

const mutations = {
  setName (state, data) {
    state.name = data
   }
}
const actions = {
   setActionName ({ commit },data) { 
    commit('setName',data)
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
  1. 使用vuex
<template>
 <div> 
    <div class="div1">
        vue3使用vuex
         <div>获取 state内数据: {{acount}}</div>
         <div>获取 getters内数据: {{getAcount}}</div>
         <button @click="clickActions"> 调用actions内函数:设置acount</button>
         <button @click="clickMutations"> 调用mutations内函数:设置acount</button>
    </div> 
 </div>
</template>
<script setup>
import {computed} from 'vue'
import { useStore } from 'vuex';
 const store = new useStore();
 const acount =  computed(()=>{
      return store.state.userInfo
 })
 const getAcount =computed(()=>{return store.getters['userInfo/getName']}) 
 const clickActions = ()=>{
    store.dispatch('userInfo/setActionName','这是简书actions')
 }
 const clickMutations = ()=>{
    store.commit('userInfo/setName','这是简书mutations')
 }

 console.log(store);
</script>

三. 持久化存储vuex-persistedstate

1. 配置参数
  • createPersistedState([options])使用给定的选项创建插件的新实例。可以提供以下选项来配置您的特定需求的插件:
  • key :存储持久状态的键。(默认:vuex)
  • paths :部分持续状态的任何路径的数组。如果没有路径给出,完整的状态是持久的。(默认:[])
  • reducer :一个函数,将被调用来基于给定的路径持久化的状态。默认包含这些值。
  • subscriber :一个被调用来设置突变订阅的函数。默认为store => handler => store.subscribe(handler)
  • storage :而不是(或与)getState和setState。默认为localStorage。
  • getState :将被调用以重新水化先前持久状态的函数。默认使用storage。
  • setState :将被调用来保持给定状态的函数。默认使用storage。
  • filter :将被调用来过滤将setState最终触发存储的任何突变的函数。默认为() => true
2. vuex引用
import createPersistedState from "vuex-persistedstate";  
  • 使用一:存储整个模块

将userInfo 存储到sessionStorage里面,key指定为zyjInfo

const zyjInfo =  createPersistedState({
       key:'zyj',
       storage: window.sessionStorage,//window.localStorage
       paths: ['userInfo']
   })
  • 使用二:存储指定模块内指定参数

将userInfo 中的name参数,存储到localStorage里面,key指定为zyjName

   const userInfoName =  createPersistedState({
        key:'zyjName',
        storage: window.localStorage,//window.sessionStorage
        paths: ['userInfo.name']
    })
3. 示例
  • store 实例增加配置如下

通过vuex 的plugins引用各个插件


import {createStore} from 'vuex'
import createPersistedState from "vuex-persistedstate";  
import userInfo from './modules/user/info.js'
   // 存储整个模块
    const zyjInfo =  createPersistedState({
        key:'zyj',
        storage: window.sessionStorage,//window.localStorage
        paths: ['userInfo']
    })
   // 存储模块内的age参数
    const userInfoAge =  createPersistedState({
        key:'zyjAge',
        storage: window.sessionStorage,//window.localStorage
        paths: ['userInfo.age']
    })
   // 存储模块内的name参数
    const userInfoName =  createPersistedState({
        key:'zyjName',
        storage: window.sessionStorage,//window.localStorage
        paths: ['userInfo.name']
    })
 const store = new createStore({
    modules: {
        //数据模块化
        userInfo: userInfo
    },
  // 将各个插件引用
    plugins:[userInfoAge,userInfoName,zyjInfo]
})
export default store
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容