分享一篇vue项目规范

最近 Vue 用的比较多,而且因为公司里有实习生,当几个人写一个项目的时候,会出现很多问题,最麻烦的就是规范不统一,之前我有一篇文章是说, vue 是比较有规范的一种框架了,但是也会出现很多问题,所以我今天写了一篇规范,也顺便拿出来分享一下

先说下我所使用的技术站:

"dependencies": {
    "axios": "^0.17.1",
    "element-ui": "^2.0.5",
    "vue": "^2.5.2",
    "vue-router": "^3.0.1",
    "vuex": "^3.0.1"
  }

一:关于 axios

1.axios 默认参数添加:

main.js:

axios.defaults.timeout = 5000;
// axios.defaults.baseURL = '/api';//默认全局前缀,build 后可以直接改动这里
//或者
axios.defaults.baseURL = process.env.NODE_ENV === 'development' ? '/api' : ''
//拦截
axios.interceptors.response.use(
    response => {
    if(response.config.url === "/api/isRegisted"){
        return response;
    }

    //若框架是springBoot    
    if(response.data.code === 500) {
if (response.data.msg === '请先登录') { router.push({ path: '/login', query: {redirect: router.history.current.fullPath} }) } ElementUI.Message({ message: response.data.msg, center: true, type: 'warning' }) return Promise.reject(response.data) }   // 若框架是springMVC if (res.data && !res.data.success) { if (res.data.code === '1004') { router.push({ path: '/login', query: {redirect: router.history.current.fullPath} }) } ElementUI.Message({ message: res.data.msg, center: true, type: 'warning' }) return Promise.reject(res.data.error.message)   } if(response.data.code === 0){ return response; } }, error => { return Promise.reject(error.response.data) });

2.axios 挂载:

main.js:

Vue.prototype.axios = axios;

3.axios 封装:

main.js:

const get =  (url,params)=>{
  return new Promise((resolve, reject) => {
    axios.get(url, {params:params})
      .then(function (response) {
        resolve(response.data);
      }).catch(err=>{
reject(err)
}) }) }; const post = (url,params)=>{ return new Promise((resolve, reject) => { axios.post(url, params) .then(function (response) { resolve(response.data) }).catch(err=>{
reject(err)
}) }) }; Vue.prototype.$api = api; Vue.prototype.$get = get; Vue.prototype.$post = post;

在 .vue 页面可以直接使用 this.$get(url,params).then(res=>{}) 和 this.$post(url,params).then(res=>{})

不需要再加 catch;

如果需要对于 loading 动画有需求可以这样使用:

this.loading = true
this.$get(url,params).then(data=>{
    this.list = data.page // 对于数据的操作
}).then(()=>{
    this.loading = false
})
// 第二个 then 是不论 ajax 的结果是正常还是异常,都会触发

// 如若对于 catch 有需求则再添加 catch

  

如果仍然有其他特殊参数的请求 可以直接调用 this.axios.get();

使用 this.axios 时必须加上 catch

二. vuex

1.ajax 判断

首先 ajax 请求可以写在 actions也可以直接写在 .vue 页面里;

我们判断的依据是 回调是否需要调用页面结构来区分,

比如在 .vue 页面中 发送完请求后需要调用 this.$refs.element等,或者需要利用组件的独立性的效果时 的那就写在.vue页面,否则就写在 actions 里

3.ajax 调用

因为异步的原因,不能将 get,post挂载到 vuex 上面,
所以新增 fetch.js 页面:
import axios from 'axios'
import api from './index.js'//api页面
const get =  (url,params)=>{
  return new Promise((resolve, reject) => {
    axios.get(url, {params:params})
      .then(function (response) {
        resolve(response.data);
      }).catch(err=>{})
  })
};
const post = (url,params)=>{
  return new Promise((resolve, reject) => {
    axios.post(url, params)
      .then(function (response) {
        resolve(response.data)
      }).catch(err=>{})
  })
};
export {api,get,post};

在 vuex 页面中引入:import {api,get} from '@/api/fetch.js'
即可发起请求:
    getUser({commit}){
        get(api.info).then(data=>{
          commit('changeUser',data)
        })
    }
    
 如有特殊需要可以新引入 axios 或者在 fetch 上在进行特殊的添加

3.模块

按类型分类,将响应模块的state,mutations,actions等分别写在对应文件中,登录,注册,修改密码等写在index 中

三.路由

1.路由需登录

在创建路由时,添加的一个例子:

{

path: 'bar',

component: Bar,

meta: { requireLogin: true }

}

在需要登录的页面添加 meta:{ requireLogin: true } 这个元素

作用是在含有这个元素的页面是需要登陆后才能使用的;

起作用需要在 main.js 里设置

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requireLogin)) {
    if ([判断登录信息]) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next()
  }
})

关于详细的登录检验我都放置在了我的另一个博客中:http://www.cnblogs.com/Grewer/p/8440726.html

2.路由name;

路由都添加 name 字段,格式是路由格式的简化,采用驼峰命名,比如

{

path: '/foo/bar',

name:'fooBar',

component: Bar

}

四: api管理

1.新建src/api/index.js;

放置 api路径 要注意 axios已经有了前缀,所以这里的 api 值需要些前缀之后的路径

当路径较多时可以再多建几个文件,分类放置

2.挂载

在 main.js 里 import api from './api/index'

使用 Vue.prototype.$api = api 挂载到原型链上,

在 Vuex 里引入有 fetch页面了,这个页面已经将 api 引入了

我抽空写了一个简单的转换工具,可以简化 API 的编写:

https://www.npmjs.com/package/vueapimanage

github:https://github.com/Grewer/vueApiManage 欢迎 star

完;