vuex+axios 的开发流程记录
2019-07-26 本文已影响0人
_不能说的秘密i
相关文档
vuex: https://vuex.vuejs.org/zh/
是否有必要使用vuex
vuex是vue的状态管理, 根据官方文档的建议,小项目就尽量不要使用这个东西了,因为使用了反而可能让你的代码可读性变差, 能用 props 和 emit 解决的就用 props 和 emit 解决, 除非你的项目中有大量的组件需要共享数据
项目目录

环境装备 - server.js
用于模拟服务端返回数据, 注意监听的端口不要和 webpack-dev-server
冲突
const http = require("http");
let tips = [
{
"title": "showdoc",
"content": "一个非常适合IT团队的在线API文档、技术文档工具",
"description": "",
"bg_color": "rgb(27, 188, 155)"
},
{
"title": "API文档",
"content": "APP、web前端与服务器常用API来进行交互",
"description": "用Api-Manager可以非常方便快速地编写出美观的API文档",
"bg_color": "rgb(44, 96, 106)"
},
{
"title": "数据字典",
"content": "好的数据字典可以很方便地向别人描述你的数据库结构",
"description": "用Api-Manager可以编辑出美观的数字字典",
"bg_color": "rgb(255, 153, 0)"
},
{
"title": "说明文档",
"content": "你完全可以使用Api-Manager来编写一些工具的说明书",
"description": "也可以编写一些技术规范说明文档以供团队查阅",
"bg_color": "rgb(124, 189, 157)"
},
{
"title": "免费开源",
"content": "Api-manager完全开源免费",
"description": "你可以放心的使用, 也可以部署到自己的服务器",
"bg_color": "rgb(124, 189, 157)"
}
];
http.createServer((request, response) => {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Headers", "X-Requested-With");
response.setHeader("Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, OPTIONS");
response.setHeader("X-Powered-By", ' 3.2.1')
response.setHeader("Content-Type", "application/json;charset=utf-8");
if (request.path = "/tips") {
response.end(JSON.stringify(tips));
}
}).listen(9527);
vuex 和 axios 配置
- api/index.js 此处只是对 axios 的 request 和 response 做了简单的处理
import axios from "axios";
/**
* 请求地址
*/
axios.defaults.baseURL = 'http://localhost:9527';
/**
* 全局请求拦截器
*/
axios.interceptors.request.use(request => {
// 对请求的参数进行处理: 超时时间设置为 5000ms
request.timeout = 5000;
return request;
}, error => {
console.log('---Request Error-----');
return Promise.resolve(err);
});
/**
* 全局响应拦截器
*/
axios.interceptors.response.use(response => {
// 对响应的信息进行处理: 只返回 response.data
return response.data;
}, err => {
let {status} = err.response;
if (status === 504 || status === 404) {
console.error('Response Error['+ status +']:服务器被吃了⊙﹏⊙∥');
} else if (status === 403 || status === 401) {
console.error('Response Error['+ status +']:权限不足,请联系管理员!');
}else {
console.error('Response Error['+ status +']:未知错误');
}
return Promise.resolve(err);
});
export default axios;
- store/index vuex 配置
import Vue from "vue";
import Vuex from "vuex";
import state from "./state";
import getters from "./getters";
import mutations from "./mutations";
import actions from "./actions";
Vue.use(Vuex);
export default new Vuex.Store({
state,
getters,
mutations,
actions
});
- store/*.js
/**
* mutatio-types.js
*/
export const GET_TIPS = 'get_tips';
/**
* actions.js
*/
import axios from "../api";
import * as types from "./mutation-typs";
export default {
// 获取首页tips
async [types.GET_TIPS]({commit}) {
await axios.get('/tips').then(response => {
commit(types.GET_TIPS, response);
});
}
};
/**
* getters.js
*/
import * as types from "./mutation-typs";
export default {
[types.GET_TIPS](state) {
return state.tips;
}
}
/**
* mutations.js
*/
import * as types from "./mutation-typs";
export default {
[types.GET_TIPS](state, data) {
state.tips = data;
},
}
/**
* states
*/
export default {
tips: [],
};
- main.js 加载 vuex
import Vue from 'vue';
import App from './App';
import router from './router';
import store from "./store";
Vue.config.productionTip = false;
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
...App
});
- Home.vue
为了简化代码, 我把其他所有的代码都删除了, 只留下核心
<template>
<div>
<p v-for="(tip, index) in tips" :key="index"> {{tip}} </p>
</div>
</template>
<script>
import {GET_TIPS} from "../store/mutation-typs";
export default {
name: "Home",
async created() {
await this.$store.dispatch(GET_TIPS);
this.tips = this.$store.getters[GET_TIPS];
},
data() {
return {
tips: [],
}
}
}
</script>
几点注意事项(个人理解)
- 注意组件在使用的时候异步的问题:
async
await
-
actions.js
mutations.js
对同一个state
的操作使用的mutation-types
中的常量 - 登录注册功能可能需要将信息持久化存储到本地, 需要在
mutations
中状态改变之前存储 - actions 中的那个请求, 如果觉得这样看着不够简洁, 可以单独独立一个
api.js
放到api目录中
如下所示
/**
* store/actions.js
*/
import * as api from "../api/api";
import * as types from "./mutation-typs";
export default {
// 获取首页tips
async [types.GET_TIPS]({commit}) {
commit(types.GET_TIPS, await api.getTips());
}
};
/**
* api/api.js
*/
import axios from "./index";
export let getTips = () => {
return axios.get('/tips').then(response => {
return response;
});
};