自我激励
人在身处逆境时,适应环境的能力实在惊人。人可以忍受不幸,也可以战胜不幸,因为人有着惊人的潜力,只要立志发挥它,就一定能渡过难关。
核心概念概述
Vuex 的主要核心概念如下:
- State
- Mutation
- Action
- Getter
State
State 提供唯一的公共数据源,所有共享的数据都要统一放到Store 的State 中进行存储
// 创建store 数据源,提供唯一公共数据
const store = new Vuex.Store({
state:{
count:0}
})
组件访问State 中数据的第一种方式:
this.$store.state.全局数据名称
组件访问State的第二种方式
// 1. 从vuex中按需导入 mapState函数
import {
mapState} from 'vuex'
通过刚才导入的mapState 函数,将当前组件需要的全局数据,映射为当前组件的computed计算属性
// 2. 将全局数据,映射为当前组件的计算属性
computed :{
...mapState(['count'])
}
Mutation
Mutation 用于变更Store中的数据
① 只能通过mutation变更 Store 数据,不可以直接操作Store中的数据
② 通过这种虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化
定义Mutation
// 定义Mutation
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
add(state) {
//变更状态
state.count ++
}
}
}
触发mutation
// 触发mutation
methods:{
handle1(){
// 触发 mutations 的第一种方式
this.$store.commit('add')
}
}
可以在触发Mutation时传递传输
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
// state 代表state中的全局数据
add(state,step) {
//变更状态
state.count+= step
}
}
}
触发mutations
btnHandler2() {
// 在调用 commit 函数,
// 触发mutations 时携带参数
this.$store.commit('addN', 3)
}
this.$store.commit () 是触发mutation 的第一种方式,触发mutations 的第二种方式
// 1. 从vuex 中按需导入 mapMutation 函数
import {
mapMutations} from 'vuex'
通过刚才导入的mapMutations函数,将需要的mutations 函数,映射为当前组件的 methods 方法
methods:{
...mapMutations(['add','addN'])
}
所以在mutations 中不能写异步的代码
Action
Action 用于处理异步任务
如果通过异步操作变更数据,必须通过Action , 而不是使用Mutation , 但是在Action中还是要通过发Mutation 的方式间接变更数据
// 定义 Action
const store = new Vuex.Store({
// ...省略其他代码
mutations: {
add(state) {
//变更状态
// 不要在mutations 函数中执行异步操作
// setTimeout(() => {
// state.count++
// }, 100)
state.count++
},
actions: {
addAsync(context) {
setTimeout(() => {
context.commit('add')
}, 1000)
}
}
}
methods: {
// 异步 地让 count 自增加一
btnHandler3() {
// 这里的 dispatch函数 专门用来触发 action
// 触发 actions 的第一种方式
this.$store.dispatch('addAsync')
}
}
触发 actions 异步任务时携带参数
// 定义 Action
const store = new Vuex.Store({
// ... 省略其他代码
mutations:{
addN(state,step){
state.count += step
}
},
actions:{
addNAsync(context,step){
setTimeout(() =>{
context.commit('addN',step)
},1000)
}
}
})
// 触发 Action
methods:{
handle(){
// 在调用 dispatch 函数,
// 触发 actions 时携带参数
this.$store.dispatch('addNAsync',5)
}
}
触发Action 的第二种方法
this.$store.dispatch() 是触发actions 的第一种方法
// 1. 从vuex 中按需导入mapActions 的函数
import {
mapActions} from 'vuex'
通过刚才导入的mapActions 函数 ,将需要的actions 函数,映射为当前组件的methods 方法:
// 2. 将指定的actions 函数,映射为当前组件的methods方法
methods:{
...mapActions(['addASync','addNASync'])
}
Getter
Getter 用于对Store 中的数据进行加工处理形成新的数据
① Getter 可以对Store 中已有数据加工处理之后形成新的数据,类似于Vue的计算属性
② Store 中数据发生变化,Getter 的数据也会跟着变化
// 定义 Getter
const store =new Vuex.Store({
state:{
count:0
},
getters: {
showNum(state) {
return '当前最新的数量是【' + state.count + '】'
}
}
})
使用Getters的第一种方式
this.$store.getters.名称
使用gettIng的第二种方式
import {
mapGetters} from 'vuex'
computed :{
...mapGetters(['showNum'])
}
男朋友不能惹生女朋友生气 女朋友生气是因为男朋友错了 不管怎样 都是男朋友错了, 男朋友错了 就必须心甘情愿的接受女朋友的任何惩罚,否则就配上 这个女朋友男朋友就是 唾弃汉,男朋友就应该多让女朋友开心 多为女朋友想想,要懂得怜香惜玉,要呵护女朋友。未完待续。。。。