vuex,概念理论什么的,我就不多说了。懂的人都懂。不懂的,请自己谷歌。本博文主要讲解它的一些常用方法和持数据的持久化(本文是以模块化来写的)。
1、安装
npm install vuex@next --save
npm i vuex-persistedstate #持久化插件
2、在根目录下新建一个store目录,再在该目录下新建一个index.ts文件(做为vuex的入口文件)
import { createStore } from 'vuex'
import createPersistedState from 'vuex-persistedstate'import user from './user' //user模块
import goods from './goods' //goods模块
//.....
//你需要哪些模块就引入哪些模块(并在对应的目录建立相应的文件)export default createStore({modules:{user,goods},plugins:[ //这个是插件,createPersistedState({storage: window.sessionStorage,key: 'vuex',paths:['user' , 'goods']})]
})
2、以user.ts模块为例
export default {namespaced:true,state:{count:10,name:'xiaobing',users:[{id:1, name:'xiaobing' , sex:1},{id:2 , name:'bingningcao' , sex:2},{id:3, name:'bingning' , sex:1}]},mutations:{setCount(state , payload){state.count = state.count + payload}},actions:{setActionsCount(context , params){context.commit('setCount' , params)}},getters:{getUserSexas1(state){return (sex)=>{return state.users.filter(item=>{return item.sex == sex})}}},
}
3、在组件/页面上使用
<template><div class="container">{{ getUserSexas1(2) }}<div>{{ store.state.user.count }}</div><div><button @click="setCount(100)">btn</button></div></div>
</template><script lang="ts" setup>import { computed } from 'vue';import { useStore , mapState } from 'vuex'; let store = useStore();// const getUserSexas1 = computed(()=>(sex)=>{// return store.getters['user/getUserSexas1'](sex)// })const getUserSexas1 = computed(()=>{return (sex)=>{return store.getters['user/getUserSexas1'](sex)}})function setCount(val){store.commit('user/setCount' , val); //只是做为提交(**Mutation**)let r = store.state.user.countconsole.log(r)}//实际中,我们是不应该直接提交(**Mutation**)里面的,只是通过(**Action**)去分发。//分发,对应user.js 中 action 里的 **setActionsCount**function setActionsCount(params){//对应user.js 中 action 里的store.dispatch('user/setActionsCount' , params) }
</script>