一.配置 Vuex4 流程
(1) yarn add vuex
(2) 创建 store/index.js 文件
(3) 使用 import 从 vuex 内 导入 createStore
import { createStore } from 'vuex'
(4) 调用 createStore 函数并定义变量 ,然后导出
cosnt store = createStore()
export default store
(5) createStore函数内分别写入 Vuex 四大天王
cosnt store = createStore({
state:{ },
mutations:{ },
actions:{ },
gtters:{ }
})
(6) main.js文件 内导入 store/index.js 这个文件
import store from './store/index'
createApp(App).use(store).mount('#app')
(7) Vue内使用 Vuex 四大天王
注意: Vue文件内 从vuex中 导入 useStore 并调用 和 定义变量
import { useStore } from 'vuex';
const store = useStore()
a: 使用state
1.store/index.js state内定义变量并给值
cosnt store = createStore({
state:{
name: '你好世界'
},
mutations:{ },
actions:{ },
gtters:{ }
})
2. Vue文件 template内 .satte.name 使用
然后这个位置就是 name值 你好世界,打开网页后 同样是 你好世界
<template>
<div>{{ store.state.name }}</div>
</template>
b:使用 mutations
1. mutations定义函数和方法
state参数表示 ,state对象
param参数表示 , 接收cmmit传递来的参数
参数写法描述: 然后这样写表示 将 state内name值 你好世界 修改为了 参数
cosnt store = createStore({
state:{
name: '你好世界'
},
mutations:{
自定义函数名(state,param){
state.name = param
}
},
actions:{ },
gtters:{ }
})
2.Vue文件内
store.commit('mutations内函数名',参数)
c: 使用 actions
1. actions定义异步函数和方法
context表示: 获取 createStore( ) 内所有四大天王
param表示: 获取 dispatch 传递来的 参数
写法描述: 这样写表示 store.dispatch 传递参数给 actions内异步函数 , 然后这个异步函数在拿着参数 传递给 mutations内函数 然后这个函数表示将 state内name 赋值为该参数 执行后 然后 state内 name 你好世界 就被修改为了 参数
cosnt store = createStore({
state:{
name: '你好世界'
},
mutations:{
自定义函数名(state,param){
state.name = param
}
},
actions:{
自定义异步函数名(context,param){
setTimeout(() => {
context.commit('mutations内函数名',param)
})
}
},
gtters:{ }
})
2.Vue文件
store.dispatch('actions内异步函数名',参数)
二.Vuex内函数使用方法
1.state: state提供唯一的公共数据资源 所有共享的数据都要统一放在store中state存储
使用 this.$store.state.xxx
模块化的 this.$store.模块名称.xxx
2.mutations: state内数据的修改只能通过 mutations 并且 mutations 必须是同步的
组件使用 this.$store.commit('mutations内函数名',参数)
模块使用 this.$store.commit('模块名/mutations内函数名',参数)
3.actions: 负责进行异步操作
组件里面使用 this.$store.dispatch('actions内异步函数',参数)
4.getters: 依赖于 state的数据 比如求数组长度 数组过滤等等 一般用于计算
组件使用: this.$getters.xxx
5.module: 开发时 避免一个状态对象过大 拆分模块使用 需要一个方法 namespaced 开启命名空间