Hand touch hands with you with vue line and a series of background (Elementary)

Disclaimer: This article is CSDN bloggers "who are prepared to be 'original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
Original link: https: //blog.csdn.net/u011565547/article/details/100010890

Hand touch hands with you with vue line and a series of background (Elementary)

Complete Project Address: VUE-Element-ADMIN

Series:

Foreword

He says good tutorial has finally come, first article mainly to talk about some preparatory work before the actual business start writing code for it, but here is not to teach basic configuration of your webpack, hot update what the principle is, webpack speed optimization and so on, there is a demand of your own google, related articles already a lot.

Directory Structure

├── build                      // 构建相关  
├── config                     // 配置相关
├── src                        // 源代码
│   ├── api                    // 所有请求
│   ├── assets                 // 主题 字体等静态资源
│   ├── components             // 全局公用组件
│   ├── directive              // 全局指令
│   ├── filtres                // 全局 filter
│   ├── icons                  // 项目所有 svg icons
│   ├── lang                   // 国际化 language
│   ├── mock                   // 项目mock 模拟数据
│   ├── router                 // 路由
│   ├── store                  // 全局 store管理
│   ├── styles                 // 全局样式
│   ├── utils                  // 全局公用方法
│   ├── vendor                 // 公用vendor
│   ├── views                   // view
│   ├── App.vue                // 入口页面
│   ├── main.js                // 入口 加载组件 初始化等
│   └── permission.js          // 权限管理
├── static                     // 第三方不打包资源
│   └── Tinymce                // 富文本
├── .babelrc                   // babel-loader 配置
├── eslintrc.js                // eslint 配置项
├── .gitignore                 // git 忽略项
├── favicon.ico                // favicon图标
├── index.html                 // html模板
└── package.json               // package.json
复制代码

Here to talk about simple file src

api sum views

Simple interception project about the company background, the background now there are about forty to fifty api module

As can be seen there are a lot of modules, and iterative business with, the module will be more and more. So here is recommended to divide the views according to the service module, and the views and api two modules-one correspondence, making it easy to maintain. As shown below:

As article module decentralization are articles related api, so no matter how projects accumulate, maintenance or api and views clear, of course, there are also some of the region's public api module, such as the seven cattle upload, remoteSearch, etc., which are placed separately on the line .

components

这里的 components 放置的都是全局公用的一些组件,如上传组件,富文本等等。一些页面级的组件建议还是放在各自views文件下,方便管理。如图:

store

这里我个人建议不要为了用 vuex 而用 vuex。就拿我司的后台项目来说,它虽然比较庞大,几十个业务模块,几十种权限,但业务之间的耦合度是很低的,文章模块和评论模块几乎是俩个独立的东西,所以根本没有必要使用 vuex 来存储data,每个页面里存放自己的 data 就行。当然有些数据还是需要用 vuex 来统一管理的,如登录token,用户信息,或者是一些全局个人偏好设置等,还是用vuex管理更加的方便,具体当然还是要结合自己的业务场景的。总之还是那句话,不要为了用vuex而用vuex!


webpack

这里是用 vue-cliwebpack-template 为基础模板构建的,如果你对这个有什么疑惑请自行google,相关的配置绍其它的文章已经介详细了,这里就不再展开了。简单说一些需要注意到地方。

jquery (本项目已移除)

管理后台不同于前台项目,会经常用到一些第三方插件,但有些插件是不得不依赖 jquery 的,如市面很多富文本基都是依赖 jquery 的,所以干脆就直接引入到项目中省事(gzip之后只有34kb,而且常年from cache,不要考虑那些吹毛求疵的大小问题,这几kb和提高的开发效率根本不能比)。但是如果第三方库的代码中出现.xxx或jQuery.xxx或window.jQuery或window.则会直接报错。要达到类似的效果,则需要使用 webpack 内置的 ProvidePlugin 插件,配置很简单,只需要

new webpack.ProvidePlugin({
  $: 'jquery' ,
  'jQuery': 'jquery'
})
复制代码

这样当 webpack 碰到 require 的第三方库中出现全局的$、jQeury和window.jQuery 时,就会使用 node_module 下 jquery 包 export 出来的东西了。

alias

When the project becomes larger, files and direct references to the relationship will be very complicated, this time on the need to use the alias of. Some people like alias pointing to src directory, and then use relative paths to find the file

resolve: {
  alias: {
    '~': resolve(__dirname, 'src')
  }
}

Use //
Import stickTop from '~ / Components / stickTop'
duplicated code

Or you can

alias: {
  'src': path.resolve(__dirname, '../src'),
  'components': path.resolve(__dirname, '../src/components'),
  'api': path.resolve(__dirname, '../src/api'),
  'utils': path.resolve(__dirname, '../src/utils'),
  'store': path.resolve(__dirname, '../src/store'),
  'router': path.resolve(__dirname, '../src/router')
}

//使用
import stickTop from 'components/stickTop'
import getArticle from 'api/article'
复制代码

There is no good or bad, right and wrong, pure personal preference and team norms.


ESLint

Whether it is personal or multiplayer cooperative project, code specification is very important. Not only does this largely avoided the basic syntax errors, but also to ensure the readability of the code. This so-called advance preparation of its profits, personal recommendation eslint + vscode to write vue, definitely have a feeling of flying in general. The effect is as:

eslintGif.gif
Each time you save, vscode can not meet the standard red eslint local rules, while also doing some simple self-correcting. Installation steps are as follows:

First install the plug-eslint

eslint1.png

After installation and configuration is complete ESLint, we continue to return VSCode extended settings, click File> Preferences> Settings to open the VSCode configuration file, add the following configuration


    "files.autoSave":"off",
    "eslint.validate": [
       "javascript",
       "javascriptreact",
       "html",
       { "language""vue""autoFix"true }
     ],
     "eslint.options": {
        "plugins": ["html"]
     }

Copy the code

So each time you save when you can do to check and fix some simple rules based on eslint .eslintrc.js you configure the root directory. Here are a rule I usually eslint address , are simple to write a comment. Each team has its own code and the specification, like unity, to build a rule eslint to upload their own npm it, such as what the team hungry config , VUE's config .

vscode plugins and configuration recommended


Package axios

我们经常遇到一些线上 的bug,但测试环境很难模拟。其实可以通过简单的配置就可以在本地调试线上环境。 这里结合业务封装了axios ,线上代码

import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 5000 // 请求超时时间
})
// request拦截器
service.interceptors.request.use(config => {
  // Do something before request is sent
  if (store.getters.token) {
    config.headers['X-Token'] = getToken() // 让每个请求携带token--['X-Token']为自定义key 请根据实际情况自行修改
  }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})
// respone拦截器
service.interceptors.response.use(
  response => response,
  /**
  * 下面的注释为通过response自定义code来标示请求状态,当code返回如下情况为权限有问题,登出并返回到登录页
  * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中
  */
  //  const res = response.data;
  //     if (res.code !== 20000) {
  //       Message({
  //         message: res.message,
  //         type: 'error',
  //         duration: 5 * 1000
  //       });
  //       // 50008:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;
  //       if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
  //         MessageBox.confirm('你已被登出,可以取消继续留在该页面,或者重新登录', '确定登出', {
  //           confirmButtonText: '重新登录',
  //           cancelButtonText: '取消',
  //           type: 'warning'
  //         }).then(() => {
  //           store.dispatch('FedLogOut').then(() => {
  //             location.reload();// 为了重新实例化vue-router对象 避免bug
  //           });
  //         })
  //       }
  //       return Promise.reject('error');
  //     } else {
  //       return response.data;
  //     }
  error => {
    console.log('err' + error)// for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  })
export default service

import request from ‘@/utils/request’
//使用
export function getInfo(params) {
return request({
url: ‘/user/info’,
method: ‘get’,
params
});
}
复制代码

比如后台项目,每一个请求都是要带 token 来验证权限的,这样封装以下的话我们就不用每个请求都手动来塞 token,或者来做一些统一的异常处理,一劳永逸。
而且因为我们的 api 是根据 env 环境变量动态切换的,如果以后线上出现了bug,我们只需配置一下 @/config/dev.env.js 再重启一下服务,就能在本地模拟线上的环境了。

module.exports = {
    NODE_ENV: '"development"',
    BASE_API: '"https://api-dev"', //修改为'"https://api-prod"'就行了
    APP_ORIGIN: '"https://wallstreetcn.com"' //为公司打个广告 pc站为vue+ssr
}

复制代码

妈妈再也不用担心我调试线上bug了。

当然这里只是简单举了个例子,axios还可以执行多个并发请求,拦截器什么的,大家自行去研究吧。


多环境

vue-cli 默认只提供了devprod两种环境。但其实正真的开发流程可能还会多一个sit或者stage环境,就是所谓的测试环境和预发布环境。所以我们就要简单的修改一下代码。其实很简单就是设置不同的环境变量

"build:prod": "NODE_ENV=production node build/build.js",
"build:sit": "NODE_ENV=sit node build/build.js",
复制代码

之后在代码里自行判断,想干就干啥

var env = process.env.NODE_ENV === 'production' ? config.build.prodEnv : config.build.sitEnv
复制代码

新版的 vue-cli 也内置了 webpack-bundle-analyzer 一个模块分析的东西,相当的好用。使用方法也很简单,和之前一样封装一个 npm script 就可以。

//package.json
 "build:sit-preview": "cross-env NODE_ENV=production env_config=sit npm_config_preview=true  npm_config_report=true node build/build.js"

//之后通过process.env.npm_config_report来判断是否来启用webpack-bundle-analyzer

var BundleAnalyzerPlugin = require(‘webpack-bundle-analyzer’).BundleAnalyzerPlugin
webpackConfig.plugins.push(new BundleAnalyzerPlugin())
复制代码

Renderings

analyzer.png
webpack-bundle-analyzer This plugin is very useful for post-code optimization What's most important is that it is enough loaded to force ~


Front and rear side interaction

Each company has its own set of development process, there is no absolute good or bad. I am here to say something about the front and rear ends of our interaction process.

Cross-domain issues

First, the front and rear end cross-domain interaction inevitably will encounter problems, our company is now wholly corssolved, if you find it troublesome back-end Division refused configured to do so, dev environment can also webpack-dev-serverof proxyto solve development environment with nginxanti Acting look like a specific configuration here is not started.

Front and rear ends of the interaction problem

In fact, we all know, the usual exchange of development costs accounted for a large part of our time, but if there is, then the front and rear ends of a good collaborative approach can solve a lot of time. Our development processes and products are front and rear ends meet to discuss the project together, after the back-end on demand, first of all define data format and api, and then mock api generate good documentation, we are the front end of the docking interface. It is recommended that a document generator Swagger . swagger is a REST APIs document generation tool that can generate on many different platforms from code comments automatically, open source, supports most languages, good community, in short, is a powerful, api documentation in the following figure (swagger automatically generated, ui ignored )

api address is no need to pass parameters, parameter passing the required type, what data format returns are quite clear.

Self distal mock

If the backend refused to help you mock the data, to mock their own front-end it is very simple. You can use mock server or use mockjs + RAP is also very convenient. Not long ago, out of the easy-mock it is quite good, but also combined with swagger. We do not look at the big front end finally face the rear end of the ~

iconfont

element-ui default icon is not much here to Amway a Bo Ali's iconfont is simply an artifact, either individual projects or project company are in use. It provides png, ai, svg three formats, but also supports the use of unicode, font-class, symbol three ways. Because it is less demanding compatibility management background, the landlord usually like to use the symbol, our sun wave background icons (all played by their landlord).

iconfont.png
Detailed and specific use of the article can see the hand touch hands with your elegant use icon


router-view

different router the same component vue. The real business scenario, this happens a lot. such as

router-view.png
I create and edit pages using the same component, by default when the two page switching does not trigger vue of created or mounted hooks, the official said that you can do through the process of change watch $ route, but in fact really is quite troublesome. And later we find out that you can simply add a unique key on the router-view, to ensure the routing switch will trigger re-rendering the hook. In this way more simple.

<router-view :key="key"></router-view>

computed: {
key() {
return this. r o u t e < / s p a n > . n a m e ! = = u n d e f i n e d ? t h i s . < s p a n c l a s s = " h l j s v a r i a b l e " > route</span>.name !== undefined? this.<span class="hljs-variable"> route.name + +new Date(): this.$route + +new Date()
}
}
复制代码


优化

有些人会觉得现在构建是不是有点慢,我司现在技术栈是容器服务,后台项目会把dist文件夹里的东西都会打包成一个docker镜像,基本步骤为

npm install
npm run build:prod
加打包镜像,一共是耗时如下
复制代码

Paste_Image.png

还是属于能接受时间的范围。 主站PC站基于nodejs、Vue实现服务端渲染,所以不仅需要依赖nodejs,而且需要利用pm2进行nodejs生命周期的管理。为了加速线上镜像构建的速度,我们利用taobao源 registry.npm.taobao.org 进行加速, 并且将一些常见的npm依赖打入了基础镜像,避免每次都需要重新下载。 这里注意下 建议不要使用cnpm install或者update 它的包都是一个link,反正会有各种诡异的bug,这里建议这样使用

npm install --registry=https://registry.npm.taobao.org
复制代码

如果你觉得慢还是有可优化的空间如使用webpack dll 或者把那些第三方vendor单独打包 external出去,或者我司现在用的是http2 可以使用AggressiveSplittingPlugin等等,这里有需求的可以自行优化。


占坑

常规占坑,这里是手摸手,带你用vue撸后台系列。 完整项目地址:vue-element-admin

发布了62 篇原创文章 · 获赞 33 · 访问量 7万+

Guess you like

Origin blog.csdn.net/Silence_Sep/article/details/101422949