vuex仓库和axios请求

创建仓库

创建一个数据仓库对象方法的参数是仓库的配置对象:
var store = new Vuex.Store({
// state代表数据仓库的数据(数据状态)
state:{
num:10,
myName:"字符串",
age:3,
time:"2019-9-26",
formartData:[]
},
// 获取仓库中的数据的属性,相当于组件computed的计算属性,其他组件可以通过仓库getters属性获取仓库数据
getters:{
// 返回值的函数 第一个参数:仓库的state属性
isAdult:function(state){
}
},
// 修改仓库中数据的属性,各个组件可以通过提交mutations来对数据进行修改
mutations:{
// mutations 属性中的函数的第一个参数是state对象
numIncrease(state){
state.num++
},
// mutations属性函数的第二个参数要设置的值
setNum(state,v){
},
setData(state,v){
state.formartData = v
}
},v // actions 如何处理数据 处理完数据一般会通过提交mutations进行对仓库数据的修改可以处理异步的数据
// mutations 修改仓库的数据
// getters 获取仓库的数据
// state:仓库的数据
actions:{
queryList(ctx){
// actions 函数的参数不再是state对象,ctx是仓库对象store
// 在actions里面不能直接对仓库的数据进行修改,必须提交mutations达到数据的修改
axios.get("/douyu/api/RoomApi/game")v .then(res=>{
// 提交mutations对应的函数
ctx.commit("setData",res.data.data[5])
}).catch(err=>{
console.log(err)
})
}
}
})





使用仓库的数据

mounted(){
// 如果在根组件配置对象注册过的store仓库对象 组件可以使用
// this.$store获取仓库对象
console.log(this.$store)
// 可以通过this.$store对象的其他属性直接获取或者修改仓库数据的值
// 这种写法不推荐使用,建议使用特定方式获取仓库数据的状态,以特定的方式修改仓库数据的状态
console.log(this.$store.state.num);
// 提交仓库的actions 可以通过dispath进行提交
// this.$store.dispatch("queryList");
this.queryList()
},
methods: {v // 映射actions的时候 相当于把仓库对象中的actions中的函数映射到本组件,必须在本组件调用一下actions中的函数
...mapActions(["queryList"]),
add(){

// 不推荐直接改变仓库数据的值
// this.$store.state.num++
// 推荐通过提交mutations改变仓库的数据
// this.$store.commit("numIncrease")
// 在提交mutations的时候 可以进行传值
this.$store.commit("setNum",100)
},
change(e){
this.$store.commit("setNum",e.target.value)
}
},
// 在本组件的computed计算里面声明一个与数据同名的一个计算结果,在实现函数把返回仓库数据的值就行
// computed: {
// num :function(){
// return this.$store.state.num
// },
// myName:function(){
// return this.$store.state.myName
// },
// age(){
// return this.$store.state.age
// } // },




v

映射


// 通过mapstate可以把数据一次性映射
// computed:mapState(["num","myName","age"])
// 通过Object.assign方法可以映射仓库的数据,添加自己的计算结果
// computed:Object.assign(mapState(["num","myName","age"]),{
// msg(){
// return "自己的组件计算结果"
// }
// })
// 也可以通过es7对象展开符的写法
computed: {
...mapState(["num","myName","age","formartData"]),
msg:function(){
return "自己计算的结果"
},
// 也可以映射仓库对象中多个getters
...mapGetters(["isAdult"]),
},
}




// 项目代理服务器的匹配对象 添加多个代理服务器

proxyTable: {
// 接口的前缀 把以/douyu为开头的接口抓发到的这个服务器

'/douyu':{
//目标服务器
target:'http://open.douyucdn.cn',
// 是否改变请求远点 如果为false 相当于重定向,一般是放在前端进行使用重定向
changeOrigin:true,
// 路径重写
pathRewrite:{
'^/douyu':""
}
}

猜你喜欢

转载自www.cnblogs.com/baixuezhemei/p/11597136.html
今日推荐