1.了解vuex的各个js文件用途
vuex一共有四个js文件组成分别是actions.js、getters.js、mutations.js、state.js
其中:
1.State:单一状态树
2.Getters:状态获取
3.Mutations:触发同步事件
4.Actions:提交mutation,可以包含异步操作
5.Module:将vuex进行分模块
官方图解:
vuex使用步骤
-
安装
npm install vuex -S
npm i -S vuex@3.6.2 -
创建store模块,分别维护
state/actions/mutations/getters
store
index.js
state.js
actions.js
mutations.js
getters.js
- 在store/index.js文件中新建vuex的store实例,并注册上面引入的各大模块
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import getters from './getters'
import actions from './actions'
import mutations from './mutations'
Vue.use(Vuex)
const store = new Vuex.Store({
state,
getters,
actions,
mutations
})
export default store
- 在main.js中导入并使用store实例
import store from './store'
new Vue({
el: '#app',
router,
store, //在main.js中导入store实例
components: {
App
},
template: '<App/>',
data: {
//自定义的事件总线对象,用于父子组件的通信
Bus: new Vue()
}
})
-
之后按要求编码,即可使用vuex的相关功能
-
vuex的核心概念:store、state、getters、mutations、actions、store
每一个Vuex应用的核心就是store(仓库),store基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。
const store = new Vuex.Store({
state, // 共同维护的一个状态,state里面可以是很多个全局状态
getters, // 获取数据并渲染
actions, // 数据的异步操作
mutations // 处理数据的唯一途径,state的改变或赋值只能在这里
})
2.vuex的使用
vue取值
state.js使用
export default{
name:'fuck you'
}
//方法调用
this.$store.state.resturantName;//不建议
getters.js使用
// 获取数据并渲染,
export default {
getname: (state) => {
return state.name;
}
}
//方法调用
this.msg = this.$store.getters.getname;
mutations.js使用
export default {
setName: (state, payload) => {
state.name = payload.name;
}
}
//方法调用
this.$store.commit('setName', {
name: '叼毛what are you doing'
});
actions使用
export default {
setNameByAsync: (context, payload) => {
setTimeout(() => {
// state.resturantName = payload.resturantName;
context.commit('setName', payload); //Action提交的是mutation
}, 3000)
},
}
//方法调用
this.$store.dispatch('setNameByAsync', {
name: '异步操作的叼毛真的叼毛'
})
3.Vuex的异步加载问题及后台调用问题
异步加载由于调用不到vue的this所以需要传一个this过去,然后谁调用this就指的谁
前端代码:
this.$store.dispatch('setNameAjax', {
_this: this,
resturantName:'海天盛宴'
})
代码:
export default {
setNameByAsync: (context, payload) => {
setTimeout(() => {
// state.resturantName = payload.resturantName;
context.commit('setName', payload); //Action提交的是mutation
}, 3000)
},
//异步加载调用后台
setNameAjax: function(context, payload) {
let _this = payload._this;
let url = _this.axios.urls.VUEX_INFO;
let params = {
resturantName: payload.resturantName
}
_this.axios.get(url, {
params: params
}).then(resp => {
if (resp.data.success) {
context.commit('setName', {
name: resp.data.msg
})
}
}).catch(err => {
})
}
}