vuex中mapState、mapGetters、mapActions、mapMutations的使用
来源:互联网 发布:夜奔什么意思网络内涵 编辑:程序博客网 时间:2024/06/16 01:11
第一步:创建store文件,添加index.js文件
第二步:安装Vuex环境npm install vuex --save,引入以下内容
import Vue from'vue'
import Vuex from'vuex'
import axiosfrom'axios'
第三步:将Vuex作为一个插件Vue.use(Vuex)
第四步:定义一个容器
let store=new Vuex.Store({
//参数与方法写在这里
//定义状态
state:{//定义在这里的数据是公用的
num:10,
navs:[]
},
getters:{
},
mutations:{
add(state,playload){
state.num+=playload.n;
},
desc(state,playload){
state.num-=playload.n
},
getNavs(state,playload){//改变state
state.navs=playload.res
}
},
actions:{
getNavs({commit}){//异步请求 通过mock模拟数据进行后台请求
console.log('store this')
console.log(this)
console.log(axios)
axios.get('http://easy-mock.com/mock/59bb998de0dc663341abbf37/http:/easy-mock.com/new/example/1/navs')
.then((response)=>{
commit('getNavs',{//触发mutation
res:response.data.data
})
})
.catch((error)=>{
console.log(error)
})
}
}
})
第五步:将store释放出去 export defaultstore
第六步:在main.js中引入store并使用。
import storefrom'./store'
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: { App }
})
第七步:在要操作的页面中引入相应的扩展对象,编辑相关操作
import {mapState,mapGetters,mapActions,mapMutations}from'vuex'
export default {
computed:{
...mapState({//获取数据
num:state=>state.num,
navs:state=>state.navs
}),
},
methods:{
//只用mapState 通过$store.commit触发mutation
add(){this.$store.commit('add',{n:10})},
desc(){this.$store.commit('desc',{n:10})},
//使用mapAction mapMutation
...mapMutations({
add:'add',
}),
//getData:function () {this.$store.dispatch('getNavs')}
...mapActions({//触发异步操作
getData:'getNavs'
}),
},
created() {
//触发一下函数使加载页面时载入
this.getData()
}
}
- vuex中mapState、mapGetters、mapActions、mapMutations的使用
- vuex中关于mapState,mapGetters,mapMutations,mapActions的作用
- vuex中关于mapState,mapGetters,mapMutations,mapActions的作用
- vuex2中使用mapMutations/mapActions/mapGetters报错解决方法
- webpack打包 vuex ...mapMutations ,...mapGetters报错解决
- vuex中的babel编译mapGetters/mapActions报错解决方法
- 记一次vuex的mapGetters无效原因
- nuxt中vuex的使用
- vuex的辅助函数mapState前面的那三个点--对象展开运算符
- Vuex的基本使用
- vuex的简单使用
- vue-cli 中使用Vuex
- vue2.0中vuex到底是干什么的?怎么使用?
- vuex使用的正确姿势
- vex使用...mapActions报错解决办法
- weex中使用数据流工具Vuex实践
- Vuex使用
- Vuex中mutations和actions的区别
- 第二章 SQL命令参考-BEGIN
- hdu 2242 考研路茫茫——空调教室 【Tarjan缩点+树上DP】 解题报告
- Git上传项目到远程仓库
- 匈牙利算法模板
- ANR理解
- vuex中mapState、mapGetters、mapActions、mapMutations的使用
- 深层次理解MVC
- Kafka理论总结(个人)
- Linux系统(四)
- 初识Docker
- [HDU4035]Maze 期望DP
- Qt--让你的客户端崩溃之前生成dump文件
- Activity启动模式与任务栈(Task)全面深入记录(下)
- virtual box 在Ubuntu14.04下启动失败解决办法