Vuex : 状态管理器
官网文档 https://v3.vuex.vuejs.org/zh/
作用 : 在vue项目中管理数据 ( 集中管理数据 ) , 方便数据的通讯
原因 : 组件通讯复杂, 方便进行组件通讯
优点 : 数据的更新是响应式的
使用 :
- 安装 yarn add vuex@3.6.2
- 创建配置store ( 在store/index.js中 )
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ 配置项/核心概念 }) export default store
- 挂载实例 ( main.js )
import store from '@/store' new Vue({ ... , store })
Vuex数据流
store/index.js 中存储修改数据
const store = new Vuex.Store({
// 存储数据,任何组件都可以访问这里的数据
state: { num:10 },
// mutations 唯一能修改数据的地方
mutations:{
// 形参1: 上面仓库的state的数据对象
// 形参2: 可选参数,接收外部传入的数据
changeNum(state,data) { state.num += data }
}
// actions 异步修改数据
actions:{
// context : 上下文对象, 里面有 commit 和 dispatch 可直接调用
// data : 可选参数, 接收外部传入的数据
changeNumAsync( context , data ){
// 专门处理网络请求
context.commit('changeNum',data)
}
}
// getters 建立快捷访问
getters:{
username(state){ return state.userinfo.xx }
}
})
state 访问数据
// 第一种
$store.state.num
// 第二种
import { mapState } from 'vuex' // 引入辅助函数mapState
computed : { ...mapState(['num']) } // 将state里的属性映射为当前组件的计算属性
mutations 修改数据
// 第一种
$store.commit( 'fn' , data )
// 第二种
import { mapMutations } from 'vuex'
methods:{ ...mapMutations(['changeNum']) }
// 将mutations 里的方法映射为当前组件的方法
// 不推荐直接用 $store.state.num 修改数据
// 原因: 调试器不能同步 / 严格模式会报错
actions 异步修改数据
// 第一种
$store.dispatch( 'fn' , data )
// 第二种
import { mapActions } from 'vuex'
methods: { ...mapActions( ['fn'] ) }
// 将actions里的方法映射为当前组件的方法
getters 建立快捷访问方式
// 第一种
$store.getters.xx
// 第二种
import { mapGetters } from 'vuex'
computed: { ...mapGetters(['xx']) }