vuex是一个数据管理仓库
官网的图如下:
在组件中操作state,mutations,actions的方式示例如下:
+ store文件的部分代码为:
export default new Vuex.Store({
state:{
num:0,
name:'aa'
},
//同步
mutations:{
setNum(state){
state.num++;
}
//另一种写法:用ES2015风格的计算属性命名功能来使用一个常量作为函数名
['setNum2'](state){
state.num++;
}
}
//异步
actions:{
actSetNum(context){
console.log(context);
setTimeout(()=>{
context.commit('setNum')
},1000)
}
}
})
-
组件中操作state
- 通过this.$store.state
- 通过计算属性
computed: { num1: function () { return this.$store.state.num } }
- 通过辅助函数
import {mapState} from 'vuex' computed:{ ...mapState({ //num2是计算属性名 num2:(state)=>{ return state.num } }) }
-
组件中操作mutations
- 通过this.$store.commit(‘setNum’) //setNum是mutations的函数名
- 通过辅助函数
import {mapMutations} from 'vuex' methods:{ ...mapMutations({ fn2:'setNum' //fn2是点击事件的事件名 }) }
-
组件中操作actions
- 通过this.$store.dispatch(‘actSetNum’) //actSetNum是actions的函数名
- 通过辅助函数
import {mapActions} from 'vuex' methods:{ ...mapActions({ fn3:'actSetNum' //fn2是点击事件的事件名 }) }
vuex的使用示例(传参)
//index.js文件
export default new Vuex.Store({
state:{
username:''
},
mutations:{
saveUserName(state,username) {
state.username = username;
}
},
actions:{
saveUserName(context,username){
context.commit('saveUserName',username);
}
}
})
//实例中调用
this.$store.dispatch('saveUserName','aa');