export default new Vuex.Store({
//存储数据
state:{
},
//方法
mutations:{
},
//计算属性
getters:{
},
//异步方法,(如ajax)
actions:{
(1)创建mutations内的方法
其中:
1、这里设置的方法,第一个参数是context上下文对象,即store实例,第二个参数是传入的参数
2、修改state中的数据,需要使用mutations内的方法,第一个形参.commit('方法名')调用,形参也可以使用es6解构赋值,{commit,state,getters,dispatch}
3、function(context/{commit,state,getters,dispatch},参数){...}
(2)调用一:通过this.$store.dispatch('函数名',参数)调用
(4)调用二:使用mapActions辅助,在methods方法里解构
methods:mapActions{['方法名']}
methods:mapActions{键名:'方法名'}
, methods:{
...mapActions(['xx','xx',...])
}
//模块
modules:{
}
})
代码示例:
store
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
//仓库对象,存放多组件共用数据
export default new Vuex.Store({
//data
state:{
num:0,
age:17,
sex:'male'
},
//methods,尽量在这里处理state中的状态
mutations:{
changeNum:function(state,val)
{
state.num=val;
}
},
//计算属性
getters:{
},
//异步方法(如ajax)
actions:{
getMsgss:function(context){
fetch('http://api.tianapi.com/txapi/ncov/index?key=4a8edfc8ac5eae9b0c5bf08157abba96')
.then(data=>data.json())
.then(res=>{console.log(res)
context.commit('changeNum',123);
})
}
},
//模块
modules:{
}
})
组件:
<template>
<div>
<button @click='getMsgss'>点击获取{{num}}</button>
</div>
</template>
<script>
import {mapState,mapActions} from 'vuex'
export default{
name:'A',
data()
{
return{
count:0
}
},
methods:{
get:function()
{
this.$store.dispatch('getMsg');
}
},
computed:{
// ...mapState(['num']),
...mapActions(['getMsgss'])
}
}
</script>
<style>
</style>