vue2-template
vue2.x 项目
项目地址
环境准备
1. 安装 node.js
根据操作系统选择安装包
下载地址:https://nodejs.org/en/download/
安装完成后,检查是否安装成功
node -v
安装成功会返回对应的版本号,这里使用的是 v14.8.1 版本
2. 安装 vue 脚手架工具
全局安装 vue-cli 脚手架工具
npm install vue-cli -g
安装完成后,检查是否安装成功
vue -V
安装成功会返回对应的版本号,这里安装的版本是 @vue/cli 4.5.11
vue2.x 项目搭建
1. 创建项目
- 使用 vue-cli 创建项目,vue create 项目名称
vue create vue2-template
- 接下来会出现配置选择页面,这里选择自定义配置
- 自定义配置项目所需功能的目录
图中框起来的两项可以不选(根据自身需求选择)
- 选择使用 vue 的版本,这里选择 2.x
然后配置 vue-router 模式(hash/history,详见官方文档),之间回车
- 配置 css 预处理器,这里选择 sass
- 选择代码格式化规则,这里选择 ESLint + Prettier
- 选择语法检查方式,这里选择 Lint on save
- 选择测试框架(第三步没有选择 Unit Testing 则跳过这一步),这里选 Jest
- 选择配置文件存放方式(独立文件中/package.json 中),这里选放在独立文件中
- 可以选择是否保存配置,这里选 Y 会让你输入配置预设名称,之后创建项目的时候可以在第 2 步中找到已保存的快捷配置
2. 配置项目
1. 配置浏览器兼容
项目根目录创建 .browserslistrc ,并添加以下内容
详细配置可见https://juejin.cn/post/6844903669524086797
> 1%
last 2 versions
not dead
2. 配置统一代码格式
项目根目录创建 .editorconfig ,并添加以下内容
# http://editorconfig.org
# top-most EditorConfig file
root = true
# Unix-style newlines with a newline ending every file
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
# Indentation override for js(x), ts(x) and vue files
[*.{js,jsx,ts,tsx,vue}]
indent_size = 2
indent_style = space
# Indentation override for css related files
[*.{css,styl,scss,less,sass}]
indent_size = 2
indent_style = space
# Indentation override for html files
[*.html]
indent_size = 2
indent_style = space
# Trailing space override for markdown file
[*.md]
insert_final_newline = false
trim_trailing_whitespace = false
# Indentation override for config files
[*.{json,yml}]
indent_size = 2
indent_style = space
配置代码格式化工具,根目录创建 .prettierrc
{
"semi": false,
"singleQuote": true,
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"proseWrap": "preserve",
"arrowParens": "avoid",
"bracketSpacing": true,
"endOfLine": "auto",
"eslintIntegration": true,
"htmlWhitespaceSensitivity": "ignore",
"ignorePath": ".prettierignore",
"jsxBracketSameLine": false,
"jsxSingleQuote": false,
"parser": "babylon",
"requireConfig": false,
"stylelintIntegration": false,
"trailingComma": "none",
"tslintIntegration": true
}
3. 配置 eslint
配置 eslint 忽略项,在根目录下创建 .eslintignore
dist/*.js
src/assets
tests/unit
public/**/*.js
配置 eslint 规则,修改根目录下的 .eslintrc.js (没有则自行创建)
配置详见官方文档
module.exports = {
root: true,
parserOptions: {
parser: 'babel-eslint',
sourceType: 'module',
},
env: {
browser: true,
node: true,
es6: true,
},
extends: ['plugin:vue/recommended', 'eslint:recommended'],
// add your custom rules here
//it is base on https://github.com/vuejs/eslint-config-vue
rules: {
'vue/max-attributes-per-line': [
2,
{
singleline: 10,
multiline: {
max: 1,
allowFirstLine: false,
},
},
],
'vue/singleline-html-element-content-newline': 'off',
'vue/multiline-html-element-content-newline': 'off',
'vue/name-property-casing': ['error', 'PascalCase'],
'vue/no-v-html': 'off',
'accessor-pairs': 2,
'arrow-spacing': [
2,
{
before: true,
after: true,
},
],
'block-spacing': [2, 'always'],
'brace-style': [
2,
'1tbs',
{
allowSingleLine: true,
},
],
camelcase: [
0,
{
properties: 'always',
},
],
'comma-dangle': [2, 'never'],
'comma-spacing': [
2,
{
before: false,
after: true,
},
],
'comma-style': [2, 'last'],
'constructor-super': 2,
curly: [2, 'multi-line'],
'dot-location': [2, 'property'],
'eol-last': 2,
eqeqeq: ['error', 'always', { null: 'ignore' }],
'generator-star-spacing': [
2,
{
before: true,
after: true,
},
],
'handle-callback-err': [2, '^(err|error)$'],
indent: [
2,
2,
{
SwitchCase: 1,
},
],
'jsx-quotes': [2, 'prefer-single'],
'key-spacing': [
2,
{
beforeColon: false,
afterColon: true,
},
],
'keyword-spacing': [
2,
{
before: true,
after: true,
},
],
'new-cap': [
2,
{
newIsCap: true,
capIsNew: false,
},
],
'new-parens': 2,
'no-array-constructor': 2,
'no-caller': 2,
'no-console': 'off',
'no-class-assign': 2,
'no-cond-assign': 2,
'no-const-assign': 2,
'no-control-regex': 0,
'no-delete-var': 2,
'no-dupe-args': 2,
'no-dupe-class-members': 2,
'no-dupe-keys': 2,
'no-duplicate-case': 2,
'no-empty-character-class': 2,
'no-empty-pattern': 2,
'no-eval': 2,
'no-ex-assign': 2,
'no-extend-native': 2,
'no-extra-bind': 2,
'no-extra-boolean-cast': 2,
'no-extra-parens': [2, 'functions'],
'no-fallthrough': 2,
'no-floating-decimal': 2,
'no-func-assign': 2,
'no-implied-eval': 2,
'no-inner-declarations': [2, 'functions'],
'no-invalid-regexp': 2,
'no-irregular-whitespace': 2,
'no-iterator': 2,
'no-label-var': 2,
'no-labels': [
2,
{
allowLoop: false,
allowSwitch: false,
},
],
'no-lone-blocks': 2,
'no-mixed-spaces-and-tabs': 2,
'no-multi-spaces': 2,
'no-multi-str': 2,
'no-multiple-empty-lines': [
2,
{
max: 1,
},
],
'no-native-reassign': 2,
'no-negated-in-lhs': 2,
'no-new-object': 2,
'no-new-require': 2,
'no-new-symbol': 2,
'no-new-wrappers': 2,
'no-obj-calls': 2,
'no-octal': 2,
'no-octal-escape': 2,
'no-path-concat': 2,
'no-proto': 2,
'no-redeclare': 2,
'no-regex-spaces': 2,
'no-return-assign': [2, 'except-parens'],
'no-self-assign': 2,
'no-self-compare': 2,
'no-sequences': 2,
'no-shadow-restricted-names': 2,
'no-spaced-func': 2,
'no-sparse-arrays': 2,
'no-this-before-super': 2,
'no-throw-literal': 2,
'no-trailing-spaces': 2,
'no-undef': 2,
'no-undef-init': 2,
'no-unexpected-multiline': 2,
'no-unmodified-loop-condition': 2,
'no-unneeded-ternary': [
2,
{
defaultAssignment: false,
},
],
'no-unreachable': 2,
'no-unsafe-finally': 2,
'no-unused-vars': [
2,
{
vars: 'all',
args: 'none',
},
],
'no-useless-call': 2,
'no-useless-computed-key': 2,
'no-useless-constructor': 2,
'no-useless-escape': 0,
'no-whitespace-before-property': 2,
'no-with': 2,
'one-var': [
2,
{
initialized: 'never',
},
],
'operator-linebreak': [
2,
'after',
{
overrides: {
'?': 'before',
':': 'before',
},
},
],
'padded-blocks': [2, 'never'],
quotes: [
2,
'single',
{
avoidEscape: true,
allowTemplateLiterals: true,
},
],
semi: [2, 'never'],
'semi-spacing': [
2,
{
before: false,
after: true,
},
],
'space-before-blocks': [2, 'always'],
'space-before-function-paren': [2, 'never'],
'space-in-parens': [2, 'never'],
'space-infix-ops': 2,
'space-unary-ops': [
2,
{
words: true,
nonwords: false,
},
],
'spaced-comment': [
2,
'always',
{
markers: [
'global',
'globals',
'eslint',
'eslint-disable',
'*package',
'!',
',',
],
},
],
'template-curly-spacing': [2, 'never'],
'use-isnan': 2,
'valid-typeof': 2,
'wrap-iife': [2, 'any'],
'yield-star-spacing': [2, 'both'],
yoda: [2, 'never'],
'prefer-const': 2,
'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0,
'object-curly-spacing': [
2,
'always',
{
objectsInObjects: false,
},
],
'array-bracket-spacing': [2, 'never'],
},
};
4. 配置 git 忽略项
根据个人情况修改 git 忽略项,修改根目录下的 .gitignore
.DS_Store
node_modules
/dist
.history
# local env files
.env.local
.env.*.local
# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# Editor directories and files
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
5. 配置 vue
根目录创建 vue.config.js
'use strict';
const devServerPort = 8080;
const name = 'vue2-template';
module.exports = {
devServer: {
port: devServerPort,
open: true,
overlay: {
warnings: false,
errors: true,
},
},
configureWebpack: {
name: name,
},
};
6. 格式化代码
根据配置代码格式,统一项目代码格式
npm run lint
7. 运行项目
配置完成后可以正常启动项目
npm run serve
核心插件
vue-router
如果是通过前面的操作步骤创建项目,则项目中已经包含 vue-router 的插件
初始化
修改 src/App.vue
<template>
<div>
<router-view />
</div>
</template>
清除 src/components、src/views 目录下的所有文件,然后在 views 下创建 index.vue
<template>
<div>IndexPage</div>
</template>
<script>
export default {
name: 'IndexPage',
};
</script>
<style lang="scss" scoped></style>
修改 src/router/index.js
import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
const routes = [
{
path: '/',
name: 'IndexPage',
component: () => import('@/views/index.vue'),
},
];
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes,
});
export default router;
路由拦截
src 下创建 permission.js
import router from './router';
router.beforeEach((to, from, next) => {
next();
});
router.afterEach(() => {});
安装进度条插件 nprogress
npm install nprogress -s
然后配置进度条插件
// permission.js
import router from './router';
// 引入进度条插件
import NProgress from 'nprogress';
import 'nprogress/nprogress.css'; // progress bar style
// 配置进度条插件
NProgress.configure({ showSpinner: false });
router.beforeEach((to, from, next) => {
// 页面跳转前显示进度条
NProgress.start();
next();
});
router.afterEach(() => {
// 页面跳转完成后关闭进度条
NProgress.done();
});
vuex
如果是通过前面的操作步骤创建项目,则项目中已经包含 vuex 的插件
初始化
使用前面步骤创建项目,会自动生成 src/store/index.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: {},
mutations: {},
actions: {},
modules: {},
});
并在 main.js 中引用