Vuex概述
- 能够在vuex中集中管理共享的数据,易于开发和后期维护
- 能够高效地实现组件之间的数据共享,提高开发效率
- 存储在vuex中的数据都是响应式的,能够保持数据与页面的同步
- 一般情况下,只有组件之间共享的数据才有必要存储到vuex中;对于组件中的私有数据,依旧存储在组件自身的data即可
- state
- Mutation
- Action
- Getter
const store = new Vuex.Store({
state:{count:0}
)}
当我在store.js文件中new 一个store对象,里面的state属性就是定义全局存储数据的敌方奥
import Vue from 'vue'
import Vuex from 'vuex'Vue.use(Vuex)export default new Vuex.Store({
state:{
count:10
},
mutations:{},
actions:{}})
上图store.js中的设置,下面是某个子组件中对count的引用,
当前最新的count值为:{{$store.state.count}}
>
export default{
data(){
return {};
}
}
查看执行结果,成功
文章图片
# 组件访问state中数据的第二种方式:
通过映射把state中的count到组件的computed属性里面
// 1.从vuex中按需导入mapState函数
import { mapState } from 'vuex'
当前最新的count值为:{{count}}
>
import { mapState } from 'vuex'
export default{
data(){
return {};
},
computed:{
...mapState(['count'])
}}
vuex推荐在mutation属性中修改store.js中的数据,而不是利用$store修改
- 只能通过Mutation变更store中的数据,不可以直接操作store中的数据
- 通过这种方式操作起来稍微繁琐一些,但是可以集中监控所有数据的变化
const store = new Vuex.store{
count:0,
mutations:{
addN(state,step){
//变更状态
state.count+=step
}
}
}
子组件中:
//触发mutation
methods:{
handle2(){
// 在调用commit函数
// 触发mutations时携带参数
this.$store.commit('addN',step)
}
}
== this.$store.commit()是触发mutations的第一种方式,触发mutations的第二种方式:==
【Vuex中的state,mutations,actions,getters属性以及其映射方法】通过刚才导入的mapMutations函数,将需要的mutations函数,映射为当前组件的methods方法:
// 1.从vuex中按需导入mapMutations函数
import {mapMutations} from 'vuex'
// 通过刚才导入的mapState函数,将需要的mutations函数,映射为当前组件的methods方法
这是第二种方法
当前最新的count值为:{{count}}
>
import { mapState,mapMutations } from 'vuex'
export default{
data(){
return {};
},
computed:{
...mapState(['count'])
},
methods:{
...mapMutations(['sub']),
btnHandler(){
this.sub
}
}}
这是第一种方法
当前最新的count值为:{{$store.state.count}}
>
export default{
data(){
return {};
},
methods:{
btnHandler1(){
// 第一种写法违法
//this.$store.state.count++
this.$store.commit('add')
},
btnHandler2(){
this.$store.commit('addN',3)
}
}
}
如果要实现异步效果,则在store.js 的actions属性中定义异步函数
actions:{
addAsync(context){
setTimeout(()=>{
context.commit('add')
},1000)
}
}
btnHandler3(){
this.$store.dispatch('addAsync')
}
在actions中不能直接修改state中的数据,必须通过context.commot()触发某个mutatuion才行,这也验证了只有mutations中定义的函数才有权力修改states中的数据
如何在触发actions异步任务的时候携带参数?很简单
actions:{
addNAsync(context,step){
setTimeout(()=>{
context.commit('addN',step)
},1000)
}
}
调用的时候
btnHandler4(){
this.$store.dispatch('addNAsync',5)
}
除了使用dispatch以外,也可以通过映射解决
subNAsync(context,step){
setTimeout(()=>{
context.commit('subN',step)
},1000)
},
在子组件中:
import { mapState,mapMutations,mapActions } from 'vuex'
...mapActions(['subNAsync']),
btnHandler3(){
this.subNAsync(5)
}
mapActions其实就是把全局的某个函数映射为子组件自己的函数了
直接调用的案例
Vuex中的核心概念
- Getter
- Getter用于对store中的数据进行加工处理形成新的数据,类似于Vue中的计算属性
- store中的数据发生变化,Getter的数据也会跟着变化
//定义Getter
const store = new Vuex.Store({
state:{
count:0
},
getters:{
showNum:state=>{
return '当前的最新的数是【'+state.count+1】'
}
)
})
使用getter的用法1:
{{$store.getters.showNum}}
使用getter的用法2:
import { mapGetters } from 'vuex'
computed:{
...mapGetters(['showNum']}
}
使用mapgetterscount值为:{{showNum}}