Vue项目架构优化

写在前面

这篇博客我将为你介绍vue的架构思想,当然这只是我根据遇到的项目总结的vue架构,这是我发现的一个小三轮,如果你有好的架构也欢迎指教哦。

好了,我们开始聊吧!

以我手撸的一个小项目 低配饿了么外卖平台 为例:线上演示地址

最初的版本

目录结构

├── src                // 生产目录
│   ├── api            // axios操作
│   ├── components     // 组件 
│   │		├── common  // 公共组件
│   │		├── admin   // 用户组件
│   │		└── seller  // 商家组件  		
│   ├── router         // 路由
│   ├── store          // vuex状态管理器
│	├── App.vue        // 首页
│   └── main.js        // Webpack 预编译入口 
复制代码

代码逻辑

很简单先访问App.vue,根据路由映射不同组件渲染页面,每个页面都有ajax请求

ajax请求长这样

getUserInfo: function() {
    this.axios.get('user/infor')
    .then(res => {
        if (res.data.status) {
            this.user = res.data.data;
        }
    })
    .catch(error => {
        console.log(error);
    });
},
复制代码

前端第一次重构

2018 4月21日

Github地址:elm1.0

目录结构

├── src                // 生产目录
│   ├── api            // axios操作
│   ├── components     // 组件 
│   ├── router         // 路由
│   ├── store          // vuex状态管理器
│	├── App.vue        // 首页
│   └── main.js        // Webpack 预编译入口
复制代码

没错只是将ajax请求都集中到了api目录下 api目录下的index.js文件

import axios from 'axios';
import store from '../store';

let httpURL = "http://www.xuguobin.club/api/elm/" //这是我服务器的api接口
let localURL = 'http://localhost/api/elm/';     //这是本地koa2的api接口
axios.defaults.baseURL = localURL;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

export default {
    //获取用户信息
    getUser() {
        return axios.get('user/infor');
    },
    //获取订单
    getOrders(orderType) {
        return axios.get('user/order?type=' + orderType);
    },
    //提交订单
    submitOrder(order) {
        return axios.get('user/submit?order=' + order);
    },
    //确认收货
    confirmOrder(orderId) {
        return axios.get('user/confirm?orderId=' + orderId);
    },
    //提交评价
    submitRating(rating) {
        return axios.get('user/rating?rating=' + rating);
    },
    //用户登录
    userLogin(user) {
        return axios.post('user/login',`username=${user.username}&password=${user.password}`);
    },
};
复制代码

这样子做,很好的将axios请求与vue页面解耦和了! 现在ajax请求长这样

getUserInfo: function() {
    this.api.getUser()
    .then(res => {
        if (res.data.status) {
            this.user = res.data.data;
        }
    })
    .catch(error => {
        console.log(error);
    });
},
复制代码

前端第二次重构

2018 7月8日 Github地址:elm2.0

目录结构

讲道理这次重构的有点过分

├── src                // 生产目录
│   └── axios           // axios操作
|         ├──base       // axios模板
|         |    ├──base.js     //axios基类
|         |    └──setting.js  //状态码
|         └── user
|               ├──cache.js     //请求函数
|               └──config.js    //配置信息
|
|   ├── base           //vue模板
│   ├── components     // 组件
|   |     ├──common    //公共组件
|   |     └──admin
|   |          ├── ui.vue             // 输出组件
|   |          ├── component.html     // template
|   |          ├── component.js       // script
|   |          └── component.less     // style
|   |  
│   ├── router         // 路由
│   ├── store          // vuex状态管理器
│	├── App.vue        // 首页
│   └── main.js        // Webpack 预编译入口
复制代码

第一次的重构虽然已经将axios请求和页面分离开来了,但是每次请求后都要验证状态码,处理错误信息。

其实这完全没有必要每个页面都来一下,这些公共操作可以一起放在axios的基类

import axios from 'axios'
import setting from './setting'

let httpURL = "http://www.xuguobin.club/api/elm/" //这是我服务器的api接口
let localURL = 'http://localhost/api/elm/';     //这是本地koa2的api接口

axios.defaults.baseURL = httpURL;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

export default class AxiosCache {
	constructor() {
		this.__config = {}
		this.__setting = setting;
		this.init();
	}

	init() {
		this.doFlushSetting(CACHE_KEY, )
	}

	doFlushSetting(key, conf) {
		if (!key && typeof key !== 'string') {
			return
		}
		this.__config[key] = conf
	}
	
	/*判断状态码*/
	resultJudge(code) {
		return code
	}
	
	/*发送请求数据*/
	sendRequest(key, options) {
		let send = this.__config[this.settingKey][key];
		let self = this;
		let baseURL = send.url;
		send.method == 'get'
			? options.data && (send.url += options.data)
			: send.data = options.data
		axios(send)
			.then(function (response) {
				send.url = baseURL;
				if (self.resultJudge(response.data.status)) {
					options.success(response.data.data)
				} else {
					options.fail
						? options.fail(response.data.data)
						: self.handleErrorCase(response.data.status)
				}
			}).catch(function (error) {
				self.handleErrorCase(error)
			})
	}
	
	/*处理错误信息*/
	handleErrorCase(error) {
		if (typeof error == 'Number') {
			console.log(error)
		} else {
			alert(error)
		}
	}
}
复制代码

而发送请求的时候,只需要这样

getUSer: function() {
     this.userCache.getUser({
         success: res => this.user = res
     })
},
复制代码

是不是很简洁。这样做,又进一步的解耦了axios操作,你可以对比我github上的elm1和elm2两个版本结构,一定会有所收获。

前端的架构追求就是尽量 完美复用和解耦

前端第三次重构?

未完待续...... 你有好的架构也欢迎你fork我的master版本! ^_^

猜你喜欢

转载自juejin.im/post/5c885bbf6fb9a049e6611a3b