文章目录
一、vuex概述
1.1 组件之间数据共享的方式
-
父向子传值:v-bind属性绑定
-
子向父传值:v-on时间绑定
-
兄弟组件之间共享数据据:EventBus
- $on 接收数据的那个组件
- $emit 发送数据的那个组件
1.2 Vuex是什么
vuex是实现全局状态管理的一种机制,实现组件之间数据的共享
1.3 好处
- 再vuex中集中管理共享的数据,易于开发维护
- 高效的实现组件之间的数据共享
- 在vuex中的数据都是响应式的,实时保持数据与页面同步
1.4 什么数据适合存储到vuex中
组件之间共享的数据,才有必要存储到vuex中;私有数据,存储到data中即可
二、使用步骤
1.安装vuex依赖包
npm install vuex --save
2. 导入vuex包
import Vuex from 'vuex
Vue.use(Vuex)
3.创建store对象
export default new Vuex.Store({
state: {
count:0
},
4.将store对象挂载到vue实例中
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
三、核心概念
3.1概述
核心概念如下:
- State
- Mutation
- Action
- Getter
3.2 State(定义数据)
提供公共数据源,所有共享的数据都要统一放到Store的State中存储
export default new Vuex.Store({
state: {
count:0
}
})
访问state数据的第一种方式
this.$store.state.数据名称
访问state数据的第二种方式
// 1.从vuex中按需导入mapState函数
import { mapState } from 'vuex'
通过刚才的mapState函数,将当前组件需要的全局数据,映射为当前组建的computed计算属性:
// 2.将全局属性,映射为当前组建的计算属性
computed:{
...mapState(['count'])
}
// 3.直接用插值表达式{{}}使用即可
3.3Mutation(变更数据)
- 只能通过 mutation 变更 Store 数据,不可以直接操作Store中的数据
- 虽然操作复杂,但是可以集中监控数据变化
使用方法1:
// 1. 定义
export default new Vuex.Store({
state: {
count:0
},
mutations: {
add(state){
//变更值
state.count++
}
}
})
// 2.触发
methods:{
handlel(){
// commit 的作用就是调用某个 mutation 函数
this.$store.commit('add')
}
}
mutation传递参数
// 1. 在mutation中定义
addN(state,step){
state.count+=step
}
// 2.调用
this.$store.commit('addN',3)
使用方法2:
// 1.从vuex中按需导入mapMutations函数
import { mapMutations } from 'vuex'
// 2将指定的 mutations 函数,映射为当前组件的 methods 函数
methods:{
...mapMutations(['add','addN'])
}
3.4Action
注意:不能在mutations函数中,执行异步操作(一秒后数字加一)
// 1.定义
mutations: {
add(state){
//变更值
state.count++
}
}
actions:{
// 一秒钟之后实现add方法
addAsync(context){
setTimeout(() => {
context.commit('add')
},1000)
}
}
// 2.触发
this.$store.dispatch('addAsync')
触发actions异步任务时携带参数:
// 1.发请求时带参数
this.$store.dispatch('addNAsync',5)
// 2.actions中携带
addNAsync(context,step){
setTimeout(() => {
context.commit('addN',step)
},1000)
}
// 3.mutations中携带
addN(state.step){
state.count += step
}
触发actions的第二种方式
// 1.从vuex中按需导入 mapActions 函数
import { mapActions } from 'vuex'
// 2.将指定的 actions函数,映射为当前组件的 methods函数
methods:{
...mapActions(['addASync','addNASync'])
}
3.5Getter(用于对Store中的数据进行加工处理形成新的数据)
- Getter可以对Store中已有的数据加工处理之后形成新的数据,类似Vue的计算属性(包装)
- Store改变,Getter页改变
// 1.定义
const store = new Vuex.Store({
state:{
count:0
},
getters:{
showNum:state => {
return '当前最新的数据时【'+state.count+1'】'
}
}
})
// 2.使用
this.$store.getters.名称
//---------
// 2.2.第二种使用方式
import { mapGetters } from 'vuex'
computed:{
...mapGetters(['showNum'])
}