Vue.js介绍

Vue.js是一套用于构建用户界面的渐进式框架
Vue.js是一个MVVM框架

MVVM模式

  • Model:负责数据存储
  • View:负责页面展示
  • View Model:负责业务逻辑处理(比如Ajax请求等),对数据进行加工后交给视图展示,Vue在其中就是起到了这个角色

使用方式

  1. 在html页面使用script引入vue.js的库即可使用
  2. 使用Npm管理依赖,使用webpack打包工具对vue.js应用打包
  3. 使用vue.js官方提供的CLI脚本架很方便去创建vue.js工程雏形

功能

  1. 声明式渲染:将数据渲染进DOM系统,如使用vue.js的插值表达式
  2. 条件与循环:使用vue.js提供的v-if、v-for等标签,方便对数据进行判断、循环
  3. 双向数据绑定: 提供v-model 指令,实现Dom元素和数据变量之间双向绑定
  4. 处理用户输入:用 v-on 指令添加一个事件监听器,通过它调用在 Vue 实例中定义的方法
  5. 组件化应用构建:vue.js可定义多组件,在vue页面中引用组件

Vue2基础

环境准备

安装脚手架

1
npm install -g @vue/cli
  • -g 参数表示全局安装,这样在任意目录都可以使用vue脚本创建项目

创建项目

使用图形向导来创建 vue 项目

1
vue ui
  1. 详情中输入项目名
  2. 预设中选择手动配置项目
  3. 功能中添加 vue router 和 vuex
  4. 配置中选择版本2.XPick a linter / formatter config选择ESLint with error prevention only,之后创建项目

安装devtools

运行项目

进入项目目录,执行

1
npm run serve

配置修改

文档地址:DevServer | webpack

修改端口

前端服务器默认占用了 8080 端口

打开vue.config.js添加

1
2
3
4
5
6
7
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
// ...
devServer: {
port: 7070
}
})

添加代理

为了避免前后端服务器联调时,fetch、xhr请求产生跨域问题,需要配置代理

打开vue.config.js添加

1
2
3
4
5
6
7
8
9
10
11
12
13
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
// ...
devServer: {
port: 7070,
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true
}
}
}
})

Vue项目结构

1
2
3
4
5
6
7
PS D:\code\client> tree src
D:\code\CLIENT\SRC
├─assets
├─components
├─router
├─store
└─views
  • assets - 静态资源

  • components - 可重用组件

  • router - 路由

  • store - 数据共享

  • views - 视图组件

  • api - 跟后台交互,发送fetch、xhr请求,接收响应

  • plugins - 插件

Vue组件

Vue的组件文件以 .vue 结尾,每个组件由三部分组成

1
2
3
4
5
<template></template>

<script></script>

<style></style>
  • template - 模板部分,由它生成html代码
  • script - 代码部分,控制模板的数据来源和行为
  • style - 样式部分,一般不关心

入口组件是 App.vue

先删除原有代码,演示Hello, World例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!-- Hello, World -->
<template>
<h1>{{msg}}</h1>
</template>

<script>
export default {
data() {
return {
msg: "Hello, Vue!"
}
}
}
</script>

解释

  • export default 导出组件对象,供main.js导入使用
  • main.js中导入了template模板,由其中的h函数解析模板,生成虚拟节点,再由mount函数展示虚拟节点(html代码,不包含template标签),将结果放置于public/index.html的id选择器(#app)
  • 也可在main.js中注释导入的原有App.vue组件,导入自定义组件,修改h函数内容,即可使用自定义组件
  • 对象有一个 data 方法,返回一个对象,给 template 提供数据
  • {{}}` 在 Vue 里称之为插值表达式,用来**绑定** data 方法返回的**对象**属性,**绑定**的含义是数据发生变化时,页面显示会同步变化 ### 文本插值
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    <template>
    <div>
    <h1>{{ name }}</h1>
    <h1>{{ age > 60 ? '老年' : '青年' }}</h1>
    </div>
    </template>
    <script>
    const options = {
    data: function () {
    return { name: '张三', age: 70 };
    }
    };
    export default options;
    </script>
    * `{{}}
    里只能绑定一个属性,绑定多个属性需要用多个 {{}} 分别绑定
  • template内只能有一个根元素(Vue2中)
  • 插值内可以进行简单的表达式计算

属性绑定

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<template>
<div>
<div><input type="text" v-bind:value="name"></div>
<div><input type="date" v-bind:value="birthday"></div>
<div><input type="text" :value="age"></div>
</div>
</template>
<script>
const options = {
data: function () {
return { name: '王五', birthday: '1995-05-01', age: 20 };
}
};
export default options;
</script>
  • 简写方式:可以省略 v-bind 只保留冒号
  • v-bind:value="name",此时name会被解析成一个变量,若是在data函数中没有找到,会显示找不到错误
  • :value="5"时,找不到对应的绑定属性,会当成表达式进行解析,解析成对应数据类型的数据

事件绑定

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<template>
<div>
<div><input type="button" value="点我执行m1" v-on:click="m1"></div>
<div><input type="button" value="点我执行m2" @click="m2"></div>
<div>{{count}}</div>
</div>
</template>
<script>
const options = {
data: function () {
return { count: 0 };
},
methods: {
m1() {
this.count ++;
console.log("m1")
},
m2() {
this.count --;
console.log("m2")
}
}
};
export default options;
</script>
  • 简写方式:可以把 v-on: 替换为 @
  • 在 methods 方法中的 this 代表的是 data 函数返回的数据对象

双向绑定

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<template>
<div>
<div>
<label for="">请输入姓名</label>
<input type="text" v-model="name">
</div>
<div>
<label for="">请输入年龄</label>
<input type="text" v-model="age">
</div>
<div>
<label for="">请选择性别</label>
男 <input type="radio" value="男" v-model="sex">
女 <input type="radio" value="女" v-model="sex">
</div>
<div>
<label for="">请选择爱好</label>
游泳 <input type="checkbox" value="游泳" v-model="fav">
打球 <input type="checkbox" value="打球" v-model="fav">
健身 <input type="checkbox" value="健身" v-model="fav">
</div>
</div>
</template>
<script>
const options = {
data: function () {
return { name: '', age: null, sex:'男' , fav:['打球']};
},
methods: {
}
};
export default options;
</script>
  • 用 v-model 实现双向绑定,即
    • javascript 数据可以同步到表单标签
    • 反过来用户在表单标签输入的新值也会同步到 javascript 这边
  • 双向绑定只适用于表单这种带【输入】功能的标签,其它标签的数据绑定,单向就足够了
  • 复选框这种标签,双向绑定的 javascript 数据类型一般用数组

计算属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<template>
<div>
<h2>{{fullName}}</h2> <!-- 计算属性 -->
<!-- <h2>{{firstName + lastName}}</h2> 表达式数据拼接 -->
<!-- <h2>{{fullName()}}</h2> 普通方法调用 -->
</div>
</template>
<script>
const options = {
data: function () {
return { firstName: '三', lastName: '张' };
},
/* methods: {
fullName() {
console.log('进入了 fullName')
return this.lastName + this.firstName;
}
},*/
computed: {
fullName() {
console.log('进入了 fullName')
return this.lastName + this.firstName;
}
}
};
export default options;
  • 普通方法调用必须加 (),没有缓存功能
  • 计算属性使用时就把它当属性来用,不加 (),有缓存功能:
    • 一次计算后,会将结果缓存,下次再计算时,只要数据没有变化,不会重新计算,直接返回缓存结果

axios

axios 的底层是用了 XMLHttpRequest(xhr)方式发送请求和接收响应,xhr相对于fetch api来说,功能更强大,但由于是比较老的api,不支持Promise,axios对xhr进行了封装,使之支持Promise,并提供了对请求、响应的统一拦截功能

安装

1
npm install axios -S

导入

1
import axios from 'axios'
  • axios 默认导出一个对象,这里的 import 导入的就是它默认导出的对象

方法

请求 备注
axios(url[, config]) 发起一个GET请求(默认请求方式)
axios.get(url[, config]) 发起一个GET请求
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]]) 发起一个POST请求
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
  • config - 选项对象,例如查询参数、请求头
  • data - 请求体数据,默认的是json格式数据
  • get、head 请求无法携带请求体,这应当是浏览器的限制所致(xhr、fetch api均有限制)
  • options、delete请求可以通过config中的data携带请求体

例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<template>
<div>
<input type="button" value="获取远程数据" @click="sendReq()">
</div>
</template>
<script>
import axios from 'axios'
const options = {
methods: {
async sendReq() {
// 1. get, post
// const resp = await axios.get('/api/a2');
// const resp = await axios.post('/api/a2');

// 2. 发送请求头
// const resp = await axios.post('/api/a3',{},{
// headers:{
// Authorization:'abc'
// }
// });

// 3. 发送请求时携带查询参数 ?name=xxx&age=xxx
// const name = encodeURIComponent('&&&');//&&&会当作特殊字符,而不是普通字符
// const age = 18;
// const resp = await axios.post(`/api/a4?name=${name}&age=${age}`);

// 不想拼串、处理特殊字符,使用下面的办法
// const resp = await axios.post('/api/a4', {}, {
// params: {
// name:'&&&&',
// age: 20
// }
// });

// 4. 用请求体发数据,格式为 urlencoded
// const params = new URLSearchParams();
// params.append("name", "张三");
// params.append("age", 24)
// const resp = await axios.post('/api/a4', params);

// 5. 用请求体发数据,格式为 multipart
// const params = new FormData();
// params.append("name", "李四");
// params.append("age", 30);
// const resp = await axios.post('/api/a5', params);

// 6. 用请求体发数据,格式为 json
const resp = await axios.post('/api/a5json', {
name: '王五',
age: 50
});

console.log(resp);
}
}
};
export default options;
</script>

创建实例

1
const _axios = axios.create(config);
  • axios对象可以直接使用,但使用的是默认的设置
  • axios.create创建的对象,可以覆盖默认设置,config见下面说明

常见的 config 项有

名称 含义
baseURL 将自动加在 url 前面
headers 请求头,类型为简单对象
params 跟在 URL 后的请求参数,类型为简单对象或 URLSearchParams
data 请求体,类型有简单对象、FormData、URLSearchParams、File 等
withCredentials 跨域时是否携带 Cookie 等凭证,默认为 false
responseType 响应类型,默认为 json

1
2
3
4
5
6
const _axios = axios.create({
baseURL: 'http://localhost:8080',
withCredentials: true
});
await _axios.post('/api/a6set')
await _axios.post('/api/a6get')
  • 生产环境希望xhr请求不走代理,可以用baseURL统一修改
  • 希望跨域请求携带cookie,需要配置withCredentials: true,服务器也要配置allowCredentials = true,否则浏览器获取跨域返回的cookie时会报错

响应格式

名称 含义
data 响应体数据
status 状态码
headers 响应头
  • 200 表示响应成功
  • 400 请求数据不正确 age=abc
  • 401 身份验证没通过
  • 403 没有权限
  • 404 资源不存在
  • 405 不支持请求方式 post
  • 500 服务器内部错误

请求拦截器

1
2
3
4
5
6
7
8
9
10
11
12
_axios.interceptors.request.use(
function(config) {
// 比如在这里添加统一的 headers
config.headers = {
Authorization:'abc'
}
return config;
},
function(error) {
return Promise.reject(error);
}
);

响应拦截器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
_axios.interceptors.response.use(
function(response) {
// 2xx 范围内走这里
return response;
},
function(error) {
// 超出 2xx, 比如 4xx, 5xx 走这里
if(error.response.status === 400){
console.log("请求参数不正确");
return Promise.resolve(400);
}//else if(404 500 ....).....
return Promise.reject(error);
}
);

条件渲染

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<template>
<div>
<input type="button" value="获取远程数据" @click="sendReq()">
<div class="title">学生列表</div>
<div class="thead">
<div class="row bold">
<div class="col">编号</div>
<div class="col">姓名</div>
<div class="col">性别</div>
<div class="col">年龄</div>
</div>
</div>
<div class="tbody">
<div class="row" v-if="students.length > 0">显示学生数据</div>
<div class="row" v-else>暂无学生数据</div>
</div>
</div>
</template>
<script>
import axios from '../util/myaxios'
const options = {
data: function() {
return {
students: []
};
},
methods : {
async sendReq() {
const resp = await axios.get("/api/students");
console.log(resp.data.data)
this.students = resp.data.data;
}
}
};
export default options;
</script>
<style scoped>
div {
font-family: 华文行楷;
font-size: 20px;
}

.title {
margin-bottom: 10px;
font-size: 30px;
color: #333;
text-align: center;
}

.row {
background-color: #fff;
display: flex;
justify-content: center;
}

.col {
border: 1px solid #f0f0f0;
width: 15%;
height: 35px;
text-align: center;
line-height: 35px;
}

.bold .col {
background-color: #f1f1f1;
}
</style>

列表渲染

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<template>
<div>
<!-- <input type="button" value="获取远程数据" @click="sendReq()"> -->
<div class="title">学生列表</div>
<div class="thead">
<div class="row bold">
<div class="col">编号</div>
<div class="col">姓名</div>
<div class="col">性别</div>
<div class="col">年龄</div>
</div>
</div>
<div class="tbody">
<div v-if="students.length > 0">
<div class="row" v-for="s of students" :key="s.id">
<div class="col">{{s.id}}</div>
<div class="col">{{s.name}}</div>
<div class="col">{{s.sex}}</div>
<div class="col">{{s.age}}</div>
</div>
</div>
<div class="row" v-else>暂无学生数据</div>
</div>
</div>
</template>
<script>
import axios from '../util/myaxios'
const options = {
mounted: function(){
this.sendReq()
},
data: function() {
return {
students: []
};
},
methods : {
async sendReq() {
const resp = await axios.get("/api/students");
console.log(resp.data.data)
this.students = resp.data.data;
}
}
};
export default options;
</script>
<style scoped>
div {
font-family: 华文行楷;
font-size: 20px;
}

.title {
margin-bottom: 10px;
font-size: 30px;
color: #333;
text-align: center;
}

.row {
background-color: #fff;
display: flex;
justify-content: center;
}

.col {
border: 1px solid #f0f0f0;
width: 15%;
height: 35px;
text-align: center;
line-height: 35px;
}

.bold .col {
background-color: #f1f1f1;
}
</style>
  • v-if和v-for不能用于同一个标签
  • v-for需要配合特殊的标签属性 key 一起使用,并且 key 属性要绑定到一个能起到唯一标识作用的数据上,本例绑定到了学生编号上
  • options的mounted属性对应一个函数,此函数会在组件挂载后(准备就绪)被调用,可以在它内部发起请求,去获取学生数据

重用组件

按钮组件(路径:src/components/MyButton.vue)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<template>
<!-- :class 属性绑定的语法,将[]中的数据绑定到class属性 -->
<div class="button" :class="[type,size]">
第<slot></slot>个按钮 <!-- 占位 插槽 -->
</div>
</template>
<script>
const options = {
props: ["type", "size"] //自定义属性
};
export default options;
</script>
<style>
//省略了样式部分
</style>

使用组件(路径:src/views /View_1.vue)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<template>
<div>
<h1>父组件</h1>
<!-- 使用子组件标签,格式为子组件名使用'-'分割,如'MyButton -> my-button' -->
<my-button type="primary" size="small">1</my-button>
<my-button type="danger" size="middle">2</my-button>
<my-button type="success" size="large">3</my-button>
</div>
</template>
<script>
import MyButton from '../components/MyButton.vue'
const options = {
//选择要使用的组件
components: {
MyButton
}
};
export default options;
</script>

Vue2进阶

ElementUI

安装

1
npm install element-ui -S

注意:Vue2对用的ElementUI的主版本也是2.XXXXX

引入组件

main.js文件中添加如下内容

1
2
3
4
5
import Element from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'

Vue.use(Element)
//放置于new Vue({之前

测试,在自己的组件中使用 ElementUI 的组件

1
<el-button>按钮</el-button>

表格组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<template>
<div>
<el-table :data="students">
<el-table-column label="编号" prop="id"></el-table-column>
<el-table-column label="姓名" prop="name"></el-table-column>
</el-table>
</div>
</template>
<script>
import axios from '../util/myaxios'
const options = {
async mounted() {
const resp = await axios.get('/api/students');
this.students = resp.data.data
},
data() {
return {
students: []
}
}
}
export default options;
</script>

分页组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<template>
<div>
<el-table v-bind:data="students">
<el-table-column label="编号" prop="id"></el-table-column>
<el-table-column label="姓名" prop="name"></el-table-column>
</el-table>
<el-pagination
:total="total"
:page-size="queryDto.size"
:current-page="queryDto.page"
layout="prev,pager,next,sizes,->,total"
:page-sizes="[5,10,15,20]"
@current-change="currentChange"
@size-change="sizeChange"
></el-pagination>
</div>
</template>
<script>
import axios from '../util/myaxios'
const options = {
mounted() {
this.query();
},
methods: {
currentChange(page) {
this.queryDto.page = page;
this.query();
},
sizeChange(size){
this.queryDto.size = size;
this.query();
},
async query() {
const resp = await axios.get('/api/students/q', {
params: this.queryDto
});
this.students = resp.data.data.list;
this.total = resp.data.data.total;
}
},
data() {
return {
students: [],
total: 0,
queryDto: {
page: 1,
size: 5
}
}
}
}
export default options;
</script>
  • 三种情况都应该触发查询
    • mounted 组件挂载完成后
    • 页号变化时
    • 页大小变化时
  • 查询传参应该根据后台需求,灵活采用不同方式
    • 本例中因为是 get 请求,无法采用请求体,只能用config对象中的 params 方式传参

分页搜索

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<template>
<div>
<el-input placeholder="请输入姓名" size="mini" v-model="queryDto.name"></el-input>
<el-select placeholder="请选择性别" size="mini" v-model="queryDto.sex" clearable>
<el-option value="男"></el-option>
<el-option value="女"></el-option>
</el-select>
<el-select placeholder="请选择年龄" size="mini" v-model="queryDto.age" clearable>
<el-option value="0,20" label="0到20岁"></el-option>
<el-option value="21,30" label="21到30岁"></el-option>
<el-option value="31,40" label="31到40岁"></el-option>
<el-option value="41,120" label="41到120岁"></el-option>
</el-select>
<el-button type="primary" size="mini" @click="search()">搜索</el-button>
<el-divider></el-divider>
<el-table v-bind:data="students">
<el-table-column label="编号" prop="id"></el-table-column>
<el-table-column label="姓名" prop="name"></el-table-column>
<el-table-column label="性别" prop="sex"></el-table-column>
<el-table-column label="年龄" prop="age"></el-table-column>
</el-table>
<el-pagination :total="total" :page-size="queryDto.size" :current-page="queryDto.page"
layout="prev,pager,next,sizes,->,total" :page-sizes="[5, 10, 15, 20]" @current-change="currentChange"
@size-change="sizeChange"></el-pagination>
</div>
</template>
<script>
import axios from '../util/myaxios'
const options = {
mounted() {
this.query();
},
methods: {
currentChange(page) {
this.queryDto.page = page;
this.query();
},
sizeChange(size) {
this.queryDto.size = size;
this.query();
},
async query() {
const resp = await axios.get('/api/students/q', {
params: this.queryDto
});
this.students = resp.data.data.list;
this.total = resp.data.data.total;
},
search() {
this.query();
}
},
data() {
return {
students: [],
total: 0,
queryDto: {
name: '',
sex: '',
age: '',
page: 1,
size: 5
}
}
}
}
export default options;
</script>
  • sex 与 age 均用 '' 表示用户没有选择的情况
  • age 取值 0,20 会被 spring 转换为 new int[]{0, 20}
  • age 取值 '' 会被 spring 转换为 new int[0]

级联选择

级联选择器中选项的数据结构为

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[
{value:100, label:'主页',children:[
{value:101, label:'菜单1', children:[
{value:105, label:'子项1'},
{value:106, label:'子项2'}
]},
{value:102, label:'菜单2', children:[
{value:107, label:'子项3'},
{value:108, label:'子项4'},
{value:109, label:'子项5'}
]},
{value:103, label:'菜单3', children:[
{value:110, label:'子项6'},
{value:111, label:'子项7'}
]},
{value:104, label:'菜单4'}
]}
]

下面的例子是将后端返回的一维数组【树化】

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<template>
<el-cascader :options="ops"></el-cascader>
</template>
<script>
import axios from '../util/myaxios'
const options = {
async mounted() {
const resp = await axios.get('/api/menu')
console.log(resp.data.data)
const array = resp.data.data;

const map = new Map();

// 1. 将所有数据存入 map 集合(为了接下来查找效率)
for(const {id,name,pid} of array) {
map.set(id, {value:id, label:name, pid:pid})
}
// 2. 建立父子关系
// 3. 找到顶层对象
const top = [];
for(const obj of map.values()) {
const parent = map.get(obj.pid);
if(parent !== undefined) {
parent.children ??= [];
parent.children.push(obj);
} else {
top.push(obj)
}
}
this.ops = top;
},
data(){
return {
ops: []
}
}
};
export default options;
</script>

Vue-Router

vue 属于单页面应用,所谓的路由,就是根据浏览器路径不同,用不同的视图组件替换这个页面内容展示

配置路由

新建一个路由 js 文件,例如 src/router/example.js,内容如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import Vue from 'vue'
import VueRouter from 'vue-router'
import ContainerView from '@/views/example/ContainerView.vue' // @指的是src目录
import LoginView from '@/views/example/LoginView.vue'
import NotFoundView from '@/views/example/NotFoundView.vue'

Vue.use(VueRouter)

const routes = [
{
path:'/',
component: ContainerView
},
{
path:'/login',
component: LoginView
},
{
path:'/404',
component: NotFoundView
}
]

const router = new VueRouter({
routes
})

export default router
  • 本例中映射了 3 个路径与对应的视图组件

在 main.js 中导入自定义的路由js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import Vue from 'vue'
import ev from './views/ExampleView.vue'
import router from './router/example' // 修改这里
import store from './store'
import Element from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'

//阻止vue启动生产消息
Vue.config.productionTip = false

Vue.use(Element)
new Vue({
router,
store,
render: h => h(ev)
}).$mount('#app')

根组件是 ExampleView.vue,内容为:

1
2
3
4
5
<template>
<div class="all">
<router-view></router-view>
</div>
</template>
  • 其中 <router-view> 起到占位作用,改变路径后,该路径对应的视图组件就会占据 <router-view> 的位置,替换掉它之前的内容

动态导入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
{
path:'/',
component: () => import('@/views/example/ContainerView.vue')
},
{
path:'/login',
component: () => import('@/views/example/LoginView.vue')
},
{
path:'/404',
component: () => import('@/views/example/NotFoundView.vue')
}
]

const router = new VueRouter({
routes
})

export default router
  • 静态导入是将所有组件的 js 代码打包到一起,如果组件非常多,打包后的 js 文件会很大,影响页面加载速度
  • 动态导入是将组件的 js 代码放入独立的文件,用到时才加载

嵌套路由

组件内需要切换内容,就需要用到嵌套路由(子路由),下面的例子是在【ContainerView 组件】内定义了 3 个子路由

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
const routes = [
{
path:'/',
component: () => import('@/views/example/ContainerView.vue'),
redirect: '/c/p1', // 访问/路径,重定向至/c/p1路径
children: [
{
path:'c/p1',
component: () => import('@/views/example/container/P1View.vue')
},
{
path:'c/p2',
component: () => import('@/views/example/container/P2View.vue')
},
{
path:'c/p3',
component: () => import('@/views/example/container/P3View.vue')
}
]
},
{
path:'/login',
component: () => import('@/views/example/LoginView.vue')
},
{
path:'/404',
component: () => import('@/views/example/NotFoundView.vue')
},
{
path:'*',
redirect: '/404'
}
]

子路由变化,切换的是【ContainerView 组件】中 <router-view></router-view> 部分的内容

1
2
3
4
5
<template>
<div class="container">
<router-view></router-view>
</div>
</template>
  • redirect 可以用来重定向(跳转)到一个新的地址
  • path 的取值为*表示匹配不到其它 path 时,就会匹配它
  • 添加path:'*'而不是修改path:'/404'path:'*',是为了浏览器地址栏的显示路径为404,而不是为原有路径

ElementUI布局

通常主页要做布局,下面的代码是 ElementUI 提供的【上-【左-右】】布局

1
2
3
4
5
6
7
8
9
10
11
12
13
<template>
<div class="container">
<el-container>
<el-header></el-header>
<el-container>
<el-aside width="200px"></el-aside>
<el-main>
<router-view></router-view>
</el-main>
</el-container>
</el-container>
</div>
</template>

路由跳转

标签式

1
2
3
4
5
<el-aside width="200px">
<router-link to="/c1/p1">P1</router-link>
<router-link to="/c1/p2">P2</router-link>
<router-link to="/c1/p3">P3</router-link>
</el-aside>

编程式

1
2
3
4
5
6
7
8
<el-header>
<el-button type="primary" icon="el-icon-edit"
circle size="mini" @click="jump('/c1/p1')"></el-button>
<el-button type="success" icon="el-icon-check"
circle size="mini" @click="jump('/c1/p2')"></el-button>
<el-button type="warning" icon="el-icon-star-off"
circle size="mini" @click="jump('/c1/p3')"></el-button>
</el-header>

jump 方法

1
2
3
4
5
6
7
8
9
10
<script>
const options = {
methods : {
jump(url) {
this.$router.push(url);
}
}
}
export default options;
</script>
  • 其中 this.$router 是拿到路由对象
  • push 方法根据 url 进行跳转

导航菜单

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<el-menu router background-color="#545c64" text-color="#fff" active-text-color="#ffd04b">
<el-submenu index="/c1">
<span slot="title">
<i class="el-icon-platform-eleme"></i>
菜单1
</span>
<el-menu-item index="/c1/p1">子项1</el-menu-item>
<el-menu-item index="/c1/p2">子项2</el-menu-item>
<el-menu-item index="/c1/p3">子项3</el-menu-item>
</el-submenu>
<el-menu-item index="/c2">
<span slot="title">
<i class="el-icon-phone"></i>
菜单2
</span>
</el-menu-item>
<el-menu-item index="/c3">
<span slot="title">
<i class="el-icon-star-on"></i>
菜单3
</span>
</el-menu-item>
</el-menu>
  • 图标和菜单项文字建议用 <span slot='title'></span> 包裹起来
  • el-menu 标签上加上 router 属性,表示结合导航菜单与路由对象,此时,就可以利用菜单项的 index 属性来路由跳转

动态路由与菜单

不同的用户查询的的菜单、路由信息是不一样的

例如:访问 /api/menu/admin 返回所有的数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[
{
"id": 102,
"name": "菜单2",
"icon": "el-icon-delete-solid",
"path": "/m2",
"pid": 0,
"component": null
},
{
"id": 107,
"name": "子项3",
"icon": "el-icon-s-marketing",
"path": "/m2/c3",
"pid": 102,
"component": "C3View.vue"
}
]

访问 /api/menu/wang 返回

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[
{
"id": 103,
"name": "菜单3",
"icon": "el-icon-s-tools",
"path": "/m3",
"pid": 0,
"component": null
},
{
"id": 110,
"name": "子项6",
"icon": "el-icon-upload",
"path": "/m3/c6",
"pid": 103,
"component": "C6View.vue"
}
]

前端根据用户身份不同,动态添加路由和显示菜单

动态路由

设置父路由名称

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const routes = [
{
path:'/',
name:'c',
component: () => import('@/views/example/ContainerView.vue'),
redirect: '/c/p1',
children: [
{
path:'c/p1',
component: () => import('@/views/example/container/P1View.vue')
},...
]
}
]

设置路由方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
export function addServerRoutes(array) {
console.log(router.getRouters());
for (const { id, path, component } of array) {
if (component !== null) {
// 动态添加路由
// 参数1:父路由名称
// 参数2:路由信息对象
router.addRoute('c', {
path: path,
name: id,
component: () => import(`@/views/example/container/${component}`)
});
}
}
}
  • js 这边只保留几个固定路由,如主页、404 和 login
  • 以上方法执行时,将服务器返回的路由信息加入到名为c的父路由中去
  • 这里要注意组件路径,前面 @/views 是必须在 js 这边完成拼接的,否则 import 函数会失效

重置路由

在用户注销时应当重置路由

1
2
3
export function resetRouter() {
router.matcher = new VueRouter({ routes }).matcher
}

页面刷新

页面刷新后,会导致动态添加的路由失效,解决方法是将路由数据存入 sessionStorage

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<script>
import axios from '@/util/myaxios'
import {resetRouter, addServerRoutes} from '@/router/example'
const options = {
data() {
return {
username: 'admin'
}
},
methods: {
async login() {
resetRouter(); // 重置路由
const resp = await axios.get(`/api/menu/${this.username}`)
const array = resp.data.data;
// localStorage 即使浏览器关闭,存储的数据仍在
// sessionStorage 以标签页为单位,关闭标签页时,数据被清除
sessionStorage.setItem('serverRoutes', JSON.stringify(array))
addServerRoutes(array); // 动态添加路由
this.$router.push('/');
}
}
}
export default options;
</script>

页面刷新,重新创建路由对象时,从 sessionStorage 里恢复路由数据

1
2
3
4
5
6
7
8
9
10
const router = new VueRouter({
routes
})

// 从 sessionStorage 中恢复路由数据
const serverRoutes = sessionStorage.getItem('serverRoutes');
if(serverRoutes) {
const array = JSON.parse(serverRoutes);
addServerRoutes(array) // 动态添加路由
}

动态菜单

代码部分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<script>
const options = {
mounted() {
const serverRoutes = sessionStorage.getItem('serverRoutes');
const array = JSON.parse(serverRoutes);
const map = new Map();
for(const obj of array) {
map.set(obj.id, obj);
}
const top = [];
for(const obj of array) {
const parent = map.get(obj.pid);
if(parent) {
parent.children ??= [];
parent.children.push(obj);
} else {
top.push(obj);
}
}
this.top = top;
},
data() {
return {
top: []
}
}
}
export default options;
</script>

菜单部分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<el-menu router background-color="#545c64" text-color="#fff" active-text-color="#ffd04b" :unique-opened="true">
<template v-for="m1 of top">
<el-submenu v-if="m1.children" :key="m1.id" :index="m1.path">
<span slot="title">
<i :class="m1.icon"></i> {{m1.name}}
</span>
<el-menu-item v-for="m2 of m1.children" :key="m2.id" :index="m2.path">
<span slot="title">
<i :class="m2.icon"></i> {{m2.name}}
</span>
</el-menu-item>
</el-submenu>
<el-menu-item v-else :key="m1.id" :index="m1.path">
<span slot="title">
<i :class="m1.icon"></i> {{m1.name}}
</span>
</el-menu-item>
</template>
</el-menu>

Vuex

入门

vuex 可以在多个组件之间共享数据,并且共享的数据是【响应式】的,即数据的变更能及时渲染到模板

与之对比 localStorage 与 sessionStorage 也能共享数据,但缺点是数据并非【响应式】

首先需要定义 state 与 mutations ,一个用来读取共享数据,一个用来修改共享数据

src/store/index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

/*
读取数据,走 state, getters
修改数据,走 mutations, actions
*/
export default new Vuex.Store({
state: {
name: '',
age: 18
},
getters: {
},
mutations: {
updateName(state, name) {
state.name = name;
}
},
actions: {
},
modules: {
}
})

修改共享数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<template>
<div class="p">
<el-input placeholder="请修改用户姓名"
size="mini" v-model="name"></el-input>
<el-button type="primary" size="mini" @click="update()">修改</el-button>
</div>
</template>
<script>
const options = {
methods: {
update(){
this.$store.commit('updateName', this.name);
}
},
data () {
return {
name:''
}
}
}
export default options;
</script>
  • mutations 方法不能直接调用,只能通过 store.commit(mutation方法名, 参数) 来间接调用

读取共享数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<template>
<div class="container">
<el-container>
<el-header>
<div class="t">
欢迎您:{{ $store.state.name }}, {{ $store.state.age }}
</div>
</el-header>
<el-container>
<el-aside width="200px">
</el-aside>
<el-main>
<router-view></router-view>
</el-main>
</el-container>
</el-container>
</div>
</template>

mapState

每次去写 $store.state.name 这样的代码显得非常繁琐,可以用 vuex 生成计算属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<template>
<div class="container">
<el-container>
<el-header>
<div class="t">欢迎您:{{ name }}, {{ age }}</div>
</el-header>
<el-container>
<el-aside width="200px">
</el-aside>
<el-main>
<router-view></router-view>
</el-main>
</el-container>
</el-container>
</div>
</template>
<script>
import { mapState } from 'vuex'
const options = {
computed: {
//name() {return this.$store.state.name} },
//age() {return this.$store.state.name} },
...mapState(['name', 'age'])
}
//computed: mapState(['name', 'age']) //同理
}
export default options;
</script>
  • mapState 返回的是一个对象,对象内包含了 name() 和 age() 的这两个方法作为计算属性
  • 此对象配合 ... 展开运算符,填充入 computed 即可使用

mapMutations

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<template>
<div class="p">
<el-input placeholder="请修改用户姓名"
size="mini" v-model="name"></el-input>
<el-button type="primary" size="mini" @click="updateName(name)">修改</el-button>
</div>
</template>
<script>
import {mapMutations} from 'vuex'
const options = {
methods: {
...mapMutations(['updateName'])
},
data () {
return {
name:''
}
}
}
export default options;
</script>
  • 类似的,调用mutation修改共享数据也可以简化
  • mapMutations返回的对象中包含的方法,就会调用store.commit()来执行mutation方法
  • 注意参数传递略有不同

actions

mutations方法内不能包括修改不能立刻生效的代码,否则会造成Vuex调试工具工作不准确,必须把这些代码写在actions方法中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

/*
读取数据,走 state, getters
修改数据,走 mutations, actions
*/
import axios from '@/util/myaxios'
export default new Vuex.Store({
state: {
name: '',
age: 18
},
getters: {
},
mutations: {
updateName(state, name) {
state.name = name;
},
// 错误的用法,如果在mutations方法中包含了异步操作,会造成开发工具不准确
/* async updateServerName(state) {
const resp = await axios.get('/api/user');
const {name, age} = resp.data.data;
state.name = name;
state.age = age;
} */
updateServerName(state, user) {
const { name, age } = user;
state.name = name;
state.age = age;
}
},
actions: {
async updateServerName(context) {
const resp = await axios.get('/api/user');
context.commit('updateServerName', resp.data.data)
}
},
modules: {
}
})
  • 首先应当调用actions的updateServerName获取数据
  • 然后再由它间接调用mutations的updateServerName更新共享数据

页面使用actions的方法代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<template>
<div class="p">
<el-button type="primary" size="mini"
@click="updateServerName()">从服务器获取数据,存入store</el-button>
</div>
</template>
<script>
import { mapActions } from 'vuex'
const options = {
methods: {
...mapActions(['updateServerName'])
}
}
export default options;
</script>
  • mapActions会生成调用actions中方法的代码

  • 调用actions的代码内部等价于this.$store.dispatch('action名称', 参数),它返回的是Promise对象,可以用同步或异步方式接收结果