一、项目初始化并安装Vuex和axios
假设你的计算机已经有node环境,并安装了yarn工具。
初始化项目命令:
vue init webpack vuex-demo
cd vuex-demo
yarn
yarn add vuex axios
yarn dev
注:多个包之间使用空格分开。
如果没问题的话,访问http://localhost:8080,应该能访问。
二、Vuex的使用
1、在src下创建文件夹vuex、mutation-types.js文件和store.js文件。
mutation-types.js文件代码如下:
export const SET_AUTHORITIES = 'SET_AUTHORITIES';
store.js文件代码如下:
import Vue from 'vue';
import Vuex from 'vuex';
import userStore from './user/store';
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
userStore: userStore,
}
});
2、在vuex下创建文件夹user,在user下创建actions.js、getters.js、store.js文件。
actions.js文件代码如下:
import {
SET_AUTHORITIES,
} from '../mutation-types';
import axios from 'axios';
const LoginCheckHandle = (
{ commit },
SubData
) => new Promise((resolve, reject) => {
axios.get('/api/Travel/GetIndexData').then((res) => {
commit(SET_AUTHORITIES, res.data.data);
resolve(res.data.data);
});
});
export default {
LoginCheckHandle
};
注:action.js中使用了Promise对象,通过axios.get()方法可以发起GET请求,commit为把请求的回来的数据存到store里面,具体存到store的操作在当前目录下的store.js中,resolve(data)为把数据返回到方法的调用处,以便方法获取服务器返回的响应。
getters.js文件代码如下:
const MyAuthList = state => state.MyAuthList;
export default {
MyAuthList
};
store.js文件代码如下:
import Vue from 'vue';
import actions from './actions';
import getters from './getters';
import {
SET_AUTHORITIES,
} from '../mutation-types';
const initState = {
MyAuthList: [],
};
const mutations = {
[SET_AUTHORITIES](state, data) {
Vue.set(state, 'MyAuthList', data); // 设置store值
},
};
export default {
state: initState,
mutations,
actions,
getters,
};
3、在main.js文件中代码如下:
import Vue from 'vue';
import App from './App';
import router from './router';
import store from './vuex/store'; // 新加的
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store, // 新加的
render: h => h(App)
})
4、组件里面使用
import {
mapActions,
mapGetters
} from 'vuex';
export default {
name: 'HelloWorld',
data () {
return {
}
},
computed: {
...mapGetters([
'MyAuthList'
])
},
methods: {
...mapActions([
'LoginCheckHandle',
]),
loginHandle() {
/*
// 访问方式1,需要在...mapActions和...mapGetters中先注册
// this.GetTestList().then(res => {
// console.log(this.testList);
// });
// 访问方式2,直接访问
// this.$store.dispatch('GetTestList').then(res => {
// console.log(this.$store.state.TestStore.testList);
// });
*/
let data = [1,2,3];
this.LoginCheckHandle(data).then((res) => {
console.log(this.MyAuthList);
});
}
},
mounted() {
this.loginHandle();
}
}
说明:组件中的LoginCheckHandle()方法为vuex/user/actions.js中的方法,通过this.LoginCheckHandle()调用,在调用之前需要在…mapActions中注册,对应的…mapGetters注册的是你需要获取的store里面的项,通过this.MyAuthList访问,MyAuthList为vuex/user/getters.js中导出的名字,并且和vuex/user/store.js中的initState里面的key相同。
三、代理转发地址的配置
采用前后端完全分离的方式开发第一步要解决的问题就是得把每个请求转发到目标服务器。
打开config/index.js文件
找到proxyTable做如下配置:
proxyTable: {
'/api': {
target: 'http://119.29.81.72:8080', // 我的测试服务器地址
pathRewrite: {
'^': ''
},
changeOrigin: true
},
}
注:意思是将所有带有api的接口都转发到http://119.29.81.72:8080服务上,changeOrigin值为true,这样前端才不会发生“跨域”的错误。
修改配置后需要重启服务,这样组件中就可以使用vuex了,试一试吧!!!