学习Vue必须要了解的知识---Vuex的使用方法

Vuex是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间数据的共享。

1. Vuex的基本使用

1.安装Vuex依赖包
npm install vuex --save
2.导入Vuex包
import Vuex from 'vuex
Vue.ues(Vuex)
3.创建store对象
const store=new Vuex.store ({
state:{count:0}
})
4.将store对象挂载到Vue实例中
new Vue({
el: ‘#app’,
render:h=>h(app),
router,
store
})

2. Vuex的核心概念

1.state

组件访问state中的数据的方式一:
this.$store.state.全局数据名称
组件访问state中的数据的方式二:
//1.导入mapstore函数
import {mapstore } from ‘vuex’
//2.将当前组件需要的全局数据,映射为当前组件的computed计算属性:
computed:{
…mapstore(['count])
}

2.Mutation

用于变更store中的数据
const store=new Vuex.store ({
state: {
count:0
},
mutations: {
add(state){
state.count++
},
addN(state,step){
state.count+=step
}
},
})

//触发mutation方式一this.KaTeX parse error: Expected '}', got 'EOF' at end of input: … this.store.commit(‘add’)
},
btnHandler2(){
this.$store.commit(‘addN’,3)
}
}
//触发mutation方式二
//1.在组件中导入mapMutations函数
import {mapMutations} from ‘vuex’
//2.将需要的mutations函数,映射为当前组件的methods方法:
methods:{
…mapMutation([‘add’,‘addN’])
btnHandler(){
this.add()
},
}

3.Action

处理异步任务
const store=new Vuex.store ({
//…省略…
actions: {
addAsync(context){
setTimeout(()=>{
context.commit(‘add’)
},1000)
}
},
})
//触发Action方式一this.KaTeX parse error: Expected '}', got 'EOF' at end of input: … this.store.dispatch(‘addAsync’)
},

}
//触发mutation方式二
//1.在组件中导入mapActions函数
import {mapActions} from ‘vuex’
//2.将需要的actions函数,映射为当前组件的methods方法:
methods:{
…mapActions([‘addAsync’,‘addNAsync’])
btnHandler(){
this.addAsync()
},
}

4.getters

对store中的数据进行加工处理形成新的数据
const store=new Vuex.store ({
state: {
count:0
},
getters: {
showNum:state=>{
return ‘当前最新的数量是’+state.count
}
},
})
//触发getters方式一
this.$store.getters.名称

//触发getters方式二
//1.在组件中导入mapGetters函数
import {mapGetters} from ‘vuex’
//2.映射为当前组件的computed计算属性:
computed:{
…mapGetters(['showNum])
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值