目录
一、了解vuex中的各个js文件的用途
Vuex 运用原因:
解决前端组件传参问题,针对当前所有变量进行统一,可理解为前端数据库。
组件传参:
1.子传父;父传子
2.核心组件:state.js:存储变量
getters.js : 获取变量
mutations.js:改变变量值
actions.js :改变变量值
3.总线:vue与实例中定义变量,这个变量也是vue实例
使用步骤:
1.加载依赖 npm insatll vuex -s下载最新版本的依赖
2.导入vuex的核心4个组件,然后通过index.js加载进来
(
创建store模块,分别维护state/actions/mutations/getters
store
index.js
state.js
actions.js
mutations.js
getters.js
)
代码如下; 如 store-- index.js
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
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
//开发环境下才会引入mockjs
//process.env.MOCK为false,那么require('@/mock')就不执行;process.env.MOCK在生产环境下为false
// process.env.MOCK && require('@/mock')
import ElementUI from 'element-ui' // 新添加 1
import 'element-ui/lib/theme-chalk/index.css' // 新添加 2 ,避免后期打包样式
import App from './App'
import router from './router'
import axios from '@/api/http' //vue项目对axios的全局配置
// import axios from 'axios'
import VueAxios from 'vue-axios'
import store from './store'
Vue.use(ElementUI);//新添加 3
Vue.use(VueAxios,axios)
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
data(){
return {
Bus:new Vue({
})
}
},
components: { App },
template: '<App/>'
})
state.js
export default{
resName:'中餐厅'
}
VuePage1.vue
<template>
<div>
欢迎光临来到{{msg}}
</div>
</template>
<script>
export default {
name: 'VuePage1',
data () {
return {
}
},
computed:{
msg(){
console.log(this.$store);
return this.$store.state.resName;
}
}
}
</script>
<style>
</style>
二、利用vuex取值
取值
state.js
状态,即要全局读写的数据
const state = {
resturantName:'喜悦餐厅'
};
getters.js
获取数据并渲染,
const getters = {
resturantName: (state) => {
return state.resturantName;
}
};
三、利用vuex同步存值
注1:mutations中方法的调用方式
不能直接调用this.$store.mutations.setResturantName('KFC'),必须使用如下方式调用:
this.$store.commit(type,payload);
获取数据并渲染,
const getters = {
resturantName: (state) => {
return state.resturantName;
}
};
四、Vuex的异步加载问题及后台调用问题
export default {
setResturantNameByAsync: (context, payload) => {
console.log('xxxx');
setTimeout(() => {
console.log('yyyy');
console.log(payload)
// state.resturantName = payload.resturantName;
context.commit('setResturantName', payload); //Action提交的是mutation
}, 3000)
console.log('zzzz');
},
doAjax: (context, payload) => {
let _this = payload._this
let url = _this.axios.urls.SYSTEM_USER_DOLOGIN;
_this.axios.post(url, {}).then((response)=> {
console.log(response);
}).catch(function(error) {
console.log(error);
});
}
}