使用Vuex之前我们需要先来了解一下 什么是 Vuex? 为什么要使用 Vuex?
先来看一下官方文档怎么解释
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
简单来讲呢 Vuex 就是一种公共的状态管理器,可以管理所有组件的状态。
我们知道 Vue 是单向数据流驱动模式,而当我们在大型项目实际开发中遇到 多个组件需要共享或更改一个状态时,通过原来的传参方式在复杂的组件嵌套中或者兄弟组件中就显得尤其麻烦,而使用 Vuex 就非常简单。
先来看一下官方文档提供的这张图
使用之前需要先安装 Vuex
npm install vuex --save
在 src 目录下创建 store 目录,在 store 目录下创建 index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex) //使用 vuex 插件
export default new Vuex.Store({
})
然后还要在入口文件 main.js 中进行导入并注册
import store from './store'
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
这样的话就可以在组件中使用 Vuex 了
如在组件中使用 state 中的数据
// 组件中
this.$store.state.isLogin //获取 state 中定义的 isLogin
// store/index.js
// 定义状态
state: {
isLogin: false
},
与之对应的辅助函数写法 mapState
// 组件中引入 mapState
import {mapState} from "vuex"
// mapState 必须将数据映射到 computed 身上
computed:{
...mapState(["属性名称"]) // 数组方式
...mapState({key:state=>state.属性}) // 对象形式
}
// 使用时
this.属性名称
如在组件中使用 getters 获取 state 中的状态
// 组件中
this.$store.getters.方法名
// store/index.js
getters: {
方法名(state) {
return state.xxx;
}
},
与之对应的辅助函数写法 mapGetters
// 组件中引入 mapGetters
import {mapGetters} from "vuex"
// mapGetters 必须将数据映射到 computed 身上
computed:{
...mapGetters(["方法名称"]) // 数组方式
...mapGetters({key:方法名称}) // 对象形式
}
// 使用时
this.方法名称
如在组件中调用 actions 中定义的方法
// 组件中
this.$store.dispatch("方法名", 传递参数);
// store/index.js
actions: {
方法名: ({commit}, 传递参数) => {
//通过 commit 提交触发 mutation 中的方法
commit('mutatuon 中方法名', username)
},
},
与之对应的辅助函数写法 mapActions
// 组件中引入 mapActions
import {mapActions} from "vuex"
// mapActions 必须将数据映射到 methods 身上
methods:{
...mapActions(["方法名称"]) // 数组方式
...mapActions({key:方法名称}) // 对象形式
}
// 使用时
this.方法名称
如在组件中调用 mutations 的方法来修改状态
// 组件中
this.$store.commit('方法名', 传递参数);
// store/index.js
mutations: {
方法名(state, 接收参数) {
// state 默认参数
state.xxx = 接收参数;
}
},
与之对应的辅助函数写法 mapMutations
// 组件中引入 mapMutations
import {mapMutations} from "vuex"
// mapMutations 必须将数据映射到 methods 身上
methods:{
...mapMutations(["方法名称"]) // 数组方式
...mapMutations({key:方法名称}) // 对象形式
}
// 使用时
this.方法名称
Vuex 本地持久化
当我们刷新页面时,项目会重新加载, vuex 会重置,我们所有的状态都会回到初始状态,而有时这是我们不想看到的,使用 vuex-persistedstate 可以避免这种情况
首先需要安装 vuex-persistedstate
npm install --save vuex-persistedstate
需要在 store 目录下 index.js 中进行配置一下
import createPersistedState from "vuex-persistedstate";
const store = new Vuex.Store({
// 加上这句配置就能实现持久化,但是默认是把 satae 中的所有状态都进行了持久化
plugins: [createPersistedState()]
// 如果只想让某一个状态进行持久化,可以按照下面来进行配置
plugins: [createPersistedState({
reducer(val){
return{
// 只存储 state 中的 city
city:val.city
}
}
})],
});
更多详情 请参考:Vuex 官方文档
ok,以上就是我个人对 Vuex 的一些基本用法的总结。谢谢观看。