官网: Vuex 是什么? | Vuex (vuejs.org)
目录
介绍
1、安装
2、新建 store/index.js 专门存放 vuex
3、 在 main.js 中导入挂载到 Vue 实例上
核心概念
1、核心概念 -state 状态
1、访问Vuex中的数据
2、通过$store访问的语法
3、通过辅助函数
2、 核心概念-mutations
1.定义mutations
2.格式说明
3.组件中提交 mutations
4、辅助函数- mapMutations
3、核心概念 - actions
1.定义actions
2.组件中通过dispatch调用
3、辅助函数 -mapActions
4、 核心概念 - getters
1.定义getters
2.使用getters
2.1原始方式-$store
2.2辅助函数 - mapGetters
5、 核心概念 - module
1、模块定义 - 准备 state
2、获取模块内的state数据
3、获取模块内的getters数据
4、获取模块内的mutations方法
5、获取模块内的actions方法
Vuex模块化的使用小结
1.直接使用
2.借助辅助方法使用
介绍
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。Vuex 也集成到 Vue 的官方调试工具 devtools extension (opens new window),提供了诸如零配置的 time-travel 调试、状态快照导入导出等高级调试功能。
1、安装
npm i vuex@3
2、新建 store/index.js
专门存放 vuex
// 导入 vue
import Vue from 'vue'
// 导入 vuex
import Vuex from 'vuex'
// vuex也是vue的插件, 需要use一下, 进行插件的安装初始化
Vue.use(Vuex)// 创建仓库 store
const store = new Vuex.Store()// 导出仓库
export default store
3、 在 main.js 中导入挂载到 Vue 实例上
import Vue from 'vue'
import App from './App.vue'
//导入
import store from './store'Vue.config.productionTip = falsenew Vue({render: h => h(App),
//挂载store
}).$mount('#app')
核心概念
1、核心概念 -state 状态
tate提供唯一的公共数据源,所有共享的数据都要统一放到Store中的State中存储。
打开项目中的store.js文件,在state对象中可以添加我们要共享的数据。
// 创建仓库 store
const store = new Vuex.Store({// state 状态, 即数据, 类似于vue组件中的data,// 区别:// 1.data 是组件自己的数据, // 2.state 中的数据整个vue项目的组件都能访问到state: {count: 101}
})
1、访问Vuex中的数据
- 通过$store直接访问 —> {{ $store.state.count }}
- 通过辅助函数mapState 映射计算属性 —> {{ count }}
2、通过$store访问的语法
获取 store:1.Vue模板中获取 this.$store2.js文件中获取 import 导入 store模板中: {{ $store.state.xxx }}
组件逻辑中: this.$store.state.xxx
JS模块中: store.state.xxx
3、通过辅助函数
- mapState获取 state中的数据
1.第一步:导入mapState (mapState是vuex中的一个函数)
import { mapState } from 'vuex'
2.第二步:采用数组形式引入state属性
mapState(['count'])
上面代码的最终得到的是 类似于
count () {return this.$store.state.count
}
3.第三步:利用展开运算符将导出的状态映射给计算属性
computed: {...mapState(['count'])}
2、 核心概念-mutations
1.定义mutations
const store = new Vuex.Store({
strict: true,state: {count: 0},// 定义mutationsmutations: {}
})
开启严格模式
通过 strict: true
可以开启严格模式,开启严格模式后,直接修改state中的值会报错
state数据的修改只能通过mutations,并且mutations必须是同步的
2.格式说明
mutations是一个对象,对象中存放修改state的方法
mutations: {// 方法里参数 第一个参数是当前store的state属性// payload 载荷 运输参数 调用mutaiions的时候 可以传递参数 传递载荷addCount (state) {state.count += 1}},2.1 提供mutation函数(带参数)
mutations: {...addCount (state, count) {state.count = count}
},
3.组件中提交 mutations
this.$store.commit('addCount')2.2 提交mutation
handle ( ) {this.$store.commit('addCount', 10)
}
小tips: 提交的参数只能是一个, 如果有多个参数要传, 可以传递一个对象this.$store.commit('addCount', {count: 10
})
Vuex中的值和组件中的input双向绑定案例
App.vue
<input :value="count" @input="handleInput" type="text">export default {methods: {handleInput (e) {// 1. 实时获取输入框的值const num = +e.target.value// 2. 提交mutation,调用mutation函数this.$store.commit('changeCount', num)}}
}
store/index.js
mutations: { changeCount (state, newCount) {state.count = newCount}
},
4、辅助函数- mapMutations
mapMutations和mapState很像,它把位于mutations中的方法提取了出来,我们可以将它导入
import { mapMutations } from 'vuex'
methods: {...mapMutations(['addCount'])
}
上面代码的含义是将mutations的方法导入了methods中,等价于
methods: {// commit(方法名, 载荷参数)addCount () {this.$store.commit('addCount')}}
此时,就可以直接通过this.addCount调用了
<button @click="addCount">值+1</button>
3、核心概念 - actions
state是存放数据的,mutations是同步更新数据 (便于监测数据的变化, 更新视图等, 方便于调试工具查看变化),
actions则负责进行异步操作
说明:mutations必须是同步的
1.定义actions
new Vuex.Store({mutations: {changeCount (state, newCount) {state.count = newCount}
}
actions: {setAsyncCount (context, num) {// 一秒后, 给一个数, 去修改 numsetTimeout(() => {context.commit('changeCount', num)}, 1000)}
},
}
2.组件中通过dispatch调用
setAsyncCount () {this.$store.dispatch('setAsyncCount', 1111)
}
3、辅助函数 -mapActions
import { mapActions } from 'vuex'
methods: {...mapActions(['setAsyncCount']) setAsyncCount//为Actions中的方法名
}//mapActions映射的代码 本质上是以下代码的写法
//methods: {
// changeCountAction (n) {
// this.$store.dispatch('setAsyncCount', n)
// },
//}
直接通过 this.方法 就可以调用
核心概念 -
4、 核心概念 - getters
从state中筛选出符合条件的一些数据,这些数据是依赖state的,此时会用到getters
1.定义getters
getters: {// getters函数的第一个参数是 state// 必须要有返回值filterList: state => state.list.filter(item => item > 5)}
2.使用getters
2.1原始方式-$store
<div>{{ $store.getters.filterList }}</div>
2.2辅助函数 - mapGetters
computed: {...mapGetters(['filterList'])
}
<div>{{ filterList }}</div>
5、 核心概念 - module
如果把所有的状态都放在state中,当项目变得越来越大的时候,Vuex会变得越来越难以维护
由此,又有了Vuex的模块化
1、模块定义 - 准备 state
定义模块 user
user中管理用户的信息状态 userInfo modules/user.js
const state = {userInfo: {name: 'zs',age: 18}
}const mutations = {}const actions = {}const getters = {}export default {state,mutations,actions,getters
}
在store/index.js
文件中的modules配置项中,注册这个模块
import user from './modules/user'
import setting from './modules/setting'const store = new Vuex.Store({modules:{user}
})
使用模块中的数据, 可以直接通过模块名访问
$store.state.模块名.xxx
=> $store.state.user.userInfo
也可以通过 mapState 映射
2、获取模块内的state数据
- 直接通过模块名访问 $store.state.模块名.xxx
$store.state.user.userInfo.name
- 通过 mapState 映射:
- 默认根级别的映射 mapState([ 'xxx' ])
...mapState('user', ['userInfo']),
- 子模块的映射 :mapState('模块名', ['xxx']) - 需要开启命名空间 namespaced:true
3、获取模块内的getters数据
- 直接通过模块名访问
$store.getters['模块名/xxx ']
<div>{{ $store.getters['user/UpperCaseName'] }}</div>
- 通过 mapGetters 映射
- 默认根级别的映射
mapGetters([ 'xxx' ])
- 子模块的映射
mapGetters('模块名', ['xxx'])
- 需要开启命名空间computed:{...mapGetters('user', ['UpperCaseName']) }
- 默认根级别的映射
4、获取模块内的mutations方法
默认模块中的 mutation 和 actions 会被挂载到全局,需要开启命名空间,才会挂载到子模块。
namespaced:true
调用方式:
- 直接通过 store 调用 $store.commit('模块名/xxx ', 额外参数)
- 通过 mapMutations 映射
- 默认根级别的映射 mapMutations([ 'xxx' ])
- 子模块的映射 mapMutations('模块名', ['xxx']) - 需要开启命名空间
...mapMutations('user', ['setUser']),
modules/user.js
const mutations = {setUser (state, newUserInfo) {state.userInfo = newUserInfo}
}
5、获取模块内的actions方法
调用语法:
- 直接通过 store 调用 $store.dispatch('模块名/xxx ', 额外参数)
- 通过 mapActions 映射
- 默认根级别的映射 mapActions([ 'xxx' ])
- 子模块的映射 mapActions('模块名', ['xxx']) - 需要开启命名空间
modules/user.js
const mutations = {setUser (state, newUserInfo) {state.userInfo = newUserInfo}
}const actions = {setUserSecond (context, newUserInfo) {// 将异步在action中进行封装setTimeout(() => {// 调用mutation context上下文,默认提交的就是自己模块的action和mutationcontext.commit('setUser', newUserInfo)}, 1000)}
}
mapActions映射
<button @click="setUserSecond({ name: 'xc', age: 20 })">一秒后更新信息</button>methods:{...mapActions('user', ['setUserSecond'])
}
Vuex模块化的使用小结
1.直接使用
- state --> $store.state.模块名.数据项名
- getters --> $store.getters['模块名/属性名']
- mutations --> $store.commit('模块名/方法名', 其他参数)
- actions --> $store.dispatch('模块名/方法名', 其他参数)
2.借助辅助方法使用
1.import { mapXxxx, mapXxx } from 'vuex'
computed、methods: {
// ...mapState、...mapGetters放computed中;
// ...mapMutations、...mapActions放methods中;
...mapXxxx('模块名', ['数据项|方法']),
...mapXxxx('模块名', { 新的名字: 原来的名字 }),
}
2.组件中直接使用 属性 {{ age }}
或 方法 @click="updateAge(2)"