目录
一、概述
1.1 Vuex是什么
Vuex是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间数据的共享。
1.2 优点
- 能够在vuex中集中管理共享的数据,易于开发和后期维护。
- 能够高效地实现组件之间地数据共享,提高开发效率。
- 存储在vuex中地数据都是响应式地,能够实时保持数据与页面的同步。
1.3 应用场景
一般情况下,只有组件之间共享的数据,才有必要存储到vuex中,对于组件中的私有数据,依旧存储在组件自身的data中即可。
二、Vuex的基本使用
2.1 安装
npm install vuex --save
2.2 引入
在store/index.js文件中进行引用
import Vuex from 'vuex'
Vue.use(Vuex)
2.3 使用-创建store对象
// state中存放的就是全局共享的数据
const store = new Vuex.Store({
state: {count: 0}
})
2.4 将store对象挂载到vue实例中
new Vue({
// 将创建的共享数据对象,挂载到Vue实例中
// 所有的组件,就可以直接从store中获取全局的数据了
store,
render: h => h(App)
}).$mount('#app')
三、核心概念—非常重要
3.1 State
State提供唯一的公共的数据源,所有共享的数据都要统一放到Store的State中进行存储。
const store = new Vuex.Store({
state: {count: 0}
})
组件中访问State中全局数据的第一种方式:
this.$store.state.全局数据名称
组件中访问State中全局数据的第二种方式:
// 1. 从vuex中按需导入mapState函数
import {mapState} from 'vuex'
通过刚才导入的mapState函数,将当前组件需要的全局数据,映射为当前组件的computed计算属性:
computed: {
...mapState(['count'])
}
3.2 Mutations
用于变更Store中的全局变量,需要注意的是,在Mutations函数中执行异步操作。
注意点:
- 只能通过mutation变更store中的数据,不可以直接操作store。
- 通过这种方式虽然操作起来稍微繁琐了一些,但是可以集中监控所有数据的变化。
定义Mutation
mutations: {
add(state) {
state.count++
},
addN(state, step) {
state.count += step
},
sub(state) {
state.count--
},
subN(state, step) {
state.count -= step
}
}
触发Mutation的第一种方式
methods: {
handlerAdd(){
this.$store.commit('add')
},
// commit的作用就是调用某个Mutations函数
handlerAddN(){
this.$store.commit('addN', 2)
}
}
触发Mutation的第二种方式
<button @click="sub">-1</button>
<button @click="subN(2)">-2</button>
// 1. 从vuex中按需导入mapMutations函数
import {mapMutations} from 'vuex'
// 2. 通过刚才的mapMutations函数,将需要的mutation函数映射到组件的methods方法中
methods:{
// 注意:这里一定要是数组形式
...mapMutations(['sub', 'subN']),
// 在指定的方法中使用
// handlerSub(){
// this.sub()
// },
// handlerSubN(){
// this.subN(2)
// }
}
3.3 Actions
用于处理异步任务。如果想要通过异步操作变更数据,必须通过actions,而不能直接使用mutations,但是actions中还是要通过触发mutations的方式间接的变更数据。
定义action
actions: {
// 这里的context代指mutations
addAsync(context) {
setTimeout(() => {
context.commit('add')
}, 1000)
},
addAsyncN(context, step) {
setTimeout(() => {
context.commit('addN', step)
}, 1000)
}
},
触发action的第一种方式
methods:{
handlerAddAsync(){
this.$store.dispatch('addAsync')
},
handlerAddAsyncN(){
this.$store.dispatch('addAsyncN', 2)
}
}
触发action的第二种方式
<button @click="subAsync">subAsync-1</button>
<button @click="subAsyncN(2)">subAsync-2</button>
// 1. 从vuex中按需导入mapActions函数
import {mapActions} from 'vuex'
// 2. 将指定的actions函数,映射到当前组件的methods函数中
methods:{
...mapActions(['subAsync', 'subAsyncN']),
// handlerSubAsync(){
// this.subAsync()
// },
// handlerSubAsyncN(){
// this.subAsyncN(2)
// }
}
3.4 Getter
Getter用于对Store中的数据进行加工处理形成新的数据。
- Getter可以对Store中已有的数据加工处理之后形成新的数据,类似于Vue的计算属性。
- Store中数据发生变化,Gettrer的数据也会随之变化。
定义Getter
const store = new Vuex.Store({
// 全局共享数据
state: {
count: 0
},
// 封装state成新的数据格式
getters: {
showNum(state) {
return '当前最新的数量是【' + state.count + '】'
}
},
})
获取Getter的第一种方式
this.$store.getters.showNum
获取Getter的第二种方式
import {mapGetters} from 'vuex'
computed: {
...mapGetters(['showNum'])
}