第一步:创建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()
}
}