Vou-Router 核心知识点
Vue Router
一、Vue Router 回顾
1、路由简介
路由是一个比较广义和抽象的概念,路由的本质就是对应关系。
在开发中,路由分为:
- 后端路由
- 前端路由
后端路由
- 概念:根据不同的用户 URL 请求,返回不同的内容
- 本质:URL 请求地址与服务器资源之间的对应关系
SPA(Single Page Application)
- Ajax前端渲染(前端渲染提高性能,但是不支持浏览器的前进后退操作)
- SPA(Single Page Application)单页面应用程序:整个网站只有一个页面,内 容的变化通过Ajax局部更新实现、同时支持浏览器地址栏的前进和后退操作
- SPA实现原理之一:基于URL地址的hash(hash的变化会导致浏览器记录访问历 史的变化、但是hash的变化不会触发新的URL请求
- 在实现SPA过程中,最核心的技术点就是前端路由
前端路由
- 概念:根据不同的用户事件,显示不同的页面内容
- 本质:用户事件与事件处理函数之间的对应关系
2、实现简易前端路由
基于URL中的hash实现(点击菜单的时候改变URL的hash,根据hash的变化控制组件的切换)
案例代码实现如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<!-- 导入 vue 文件 -->
<script src="./lib/vue_2.5.22.js"></script>
</head>
<body>
<!-- 被 vue 实例控制的 div 区域 -->
<div id="app">
<!-- 切换组件的超链接 -->
<a href="#/zhuye">主页</a>
<a href="#/keji">科技</a>
<a href="#/caijing">财经</a>
<a href="#/yule">娱乐</a>
<!-- 根据 :is 属性指定的组件名称,把对应的组件渲染到 component 标签所在的位置 -->
<!-- 可以把 component 标签当做是【组件的占位符】 -->
<component :is="comName"></component>
</div>
<script>
// #region 定义需要被切换的 4 个组件
// 主页组件
const zhuye = {
template: '<h1>主页信息</h1>'
}
// 科技组件
const keji = {
template: '<h1>科技信息</h1>'
}
// 财经组件
const caijing = {
template: '<h1>财经信息</h1>'
}
// 娱乐组件
const yule = {
template: '<h1>娱乐信息</h1>'
}
// #endregion
// #region vue 实例对象
const vm = new Vue({
el: '#app',
data: {
comName: 'zhuye'
},
// 注册私有组件
components: {
zhuye,
keji,
caijing,
yule
}
})
// #endregion
// 监听 window 的 onhashchange 事件,根据获取到的最新的 hash 值,切换要显示的组件的名称
window.onhashchange = function() {
// 通过 location.hash 获取到最新的 hash 值
console.log(location.hash);
switch(location.hash.slice(1)){
case '/zhuye':
vm.comName = 'zhuye'
break
case '/keji':
vm.comName = 'keji'
break
case '/caijing':
vm.comName = 'caijing'
break
case '/yule':
vm.comName = 'yule'
break
}
}
</script>
</body>
</html>
3、vue-router
的基本使用
Vue Router
(官网:https://router.vuejs.org/zh/
)是 Vue.js
官方的路由管理器。 它和 Vue.js
的核心深度集成,可以非常方便的用于SPA
应用程序的开发。
基本使用的步骤:
- 引入相关的库文件
- 添加路由链接
- 添加路由填充位
- 定义路由组件
- 配置路由规则并创建路由实例
- 把路由挂载到
Vue
根实例中
下面看一下具体的实施过程
- 引入相关的库文件
<!-- 导入 vue 文件,为全局 window 对象挂载 Vue 构造函数 -->
<script src="./lib/vue_2.5.22.js"></script>
<!-- 导入 vue-router 文件,为全局 window 对象挂载 VueRouter 构造函数 -->
<script src="./lib/vue-router_3.0.2.js"></script>
- 添加路由链接
<!-- router-link 是 vue 中提供的标签,默认会被渲染为 a 标签 -->
<!-- to 属性默认会被渲染为 href 属性 -->
<!-- to 属性的值默认会被渲染为 # 开头的 hash 地址 -->
<router-link to="/user">User</router-link>
<router-link to="/register">Register</router-link>
- 添加路由填充位
<!-- 路由填充位(也叫做路由占位符) -->
<!-- 将来通过路由规则匹配到的组件,将会被渲染到 router-view 所在的位置 -->
<router-view></router-view>
- 定义路由组件
var User = {
template: '<div>User</div>'
}
var Register = {
template: '<div>Register</div>'
}
- 配置路由规则并创建路由实例
// 创建路由实例对象
var router = new VueRouter({
// routes 是路由规则数组
routes: [
// 每个路由规则都是一个配置对象,其中至少包含 path 和 component 两个属性:
// path 表示当前路由规则匹配的 hash 地址
// component 表示当前路由规则对应要展示的组件
{path:'/user',component: User},
{path:'/register',component: Register}
]
})
- 把路由挂载到 Vue 根实例中
new Vue({
el: '#app',
// 为了能够让路由规则生效,必须把路由对象挂载到 vue 实例对象上
router
});
完整代码实现如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<!-- 导入 vue 文件 -->
<script src="./lib/vue_2.5.22.js"></script>
<script src="./lib/vue-router_3.0.2.js"></script>
</head>
<body>
<!-- 被 vm 实例所控制的区域 -->
<div id="app">
<router-link to="/user">User</router-link>
<router-link to="/register">Register</router-link>
<!-- 路由占位符 -->
<router-view></router-view>
</div>
<script>
const User = {
template: '<h1>User 组件</h1>'
}
const Register = {
template: '<h1>Register 组件</h1>'
}
// 创建路由实例对象
const router = new VueRouter({
// 所有的路由规则
routes: [
{ path: '/user', component: User },
{ path: '/register', component: Register }
]
})
// 创建 vm 实例对象
const vm = new Vue({
// 指定控制的区域
el: '#app',
data: {},
// 挂载路由实例对象
// router: router
router
})
</script>
</body>
</html>
4、路由重定向
路由重定向指的是:用户在访问地址 A 的时候,强制用户跳转到地址 C ,从而展示特定的组件页面;
通过路由规则的 redirect 属性,指定一个新的路由地址,可以很方便地设置路由的重定向:
var router = new VueRouter({
routes: [
// 其中,path 表示需要被重定向的原地址,redirect 表示将要被重定向到的新地址
//当用户在地址栏中输入`/`,会自动的跳转到`/user`,而`/user`对应的组件为User
{path:'/', redirect: '/user'},
{path:'/user',component: User},
{path:'/register',component: Register}
]
})
具体实现的代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<!-- 导入 vue 文件 -->
<script src="./lib/vue_2.5.22.js"></script>
<script src="./lib/vue-router_3.0.2.js"></script>
</head>
<body>
<!-- 被 vm 实例所控制的区域 -->
<div id="app">
<router-link to="/user">User</router-link>
<router-link to="/register">Register</router-link>
<!-- 路由占位符 -->
<router-view></router-view>
</div>
<script>
const User = {
template: '<h1>User 组件</h1>'
}
const Register = {
template: '<h1>Register 组件</h1>'
}
// 创建路由实例对象
const router = new VueRouter({
// 所有的路由规则
routes: [
//路由重定向
{ path: '/', redirect: '/user'},
{ path: '/user', component: User },
{ path: '/register', component: Register }
]
})
// 创建 vm 实例对象
const vm = new Vue({
// 指定控制的区域
el: '#app',
data: {},
// 挂载路由实例对象
// router: router
router
})
</script>
</body>
</html>
5、嵌套路由
嵌套路由功能分析
点击父级路由链接显示模板内容
模板内容中又有子级路由链接
点击子级路由链接显示子级模板内容
下面看一下实现的步骤
父路由组件模板
- 父级路由链接
- 父组件路由填充位
<p>
<router-link to="/user">User</router-link>
<router-link to="/register">Register</router-link>
</p>
<div>
<!-- 控制组件的显示位置 -->
<router-view></router-view>
</div>
以上的内容,在前面的课程中已经实现。
子级路由模板
- 子级路由链接
- 子级路由填充位
const Register = {
template: `<div>
<h1>Register 组件</h1>
<hr/>
<router-link to="/register/tab1">Tab1</router-link>
<router-link to="/register/tab2">Tab2</router-link>
<!-- 子路由填充位置 -->
<router-view/>
</div>`
}
嵌套路由配置
父级路由通过children
属性配置子级路由
const router = new VueRouter({
routes: [
{ path: '/user', component: User },
{ path: '/register', component: Register,
// 通过 children 属性,为 /register 添加子路由规则
children: [
{ path: '/register/tab1', component: Tab1 },
{ path: '/register/tab2', component: Tab2 }
]
}
]
})
具体代码实现如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<!-- 导入 vue 文件 -->
<script src="./lib/vue_2.5.22.js"></script>
<script src="./lib/vue-router_3.0.2.js"></script>
</head>
<body>
<!-- 被 vm 实例所控制的区域 -->
<div id="app">
<router-link to="/user">User</router-link>
<router-link to="/register">Register</router-link>
<!-- 路由占位符 -->
<router-view></router-view>
</div>
<script>
const User = {
template: '<h1>User 组件</h1>'
}
//修改Register组件
const Register = {
template: `<div>
<h1>Register 组件</h1>
<hr/>
<!-- 子路由链接 -->
<router-link to="/register/tab1">tab1</router-link>
<router-link to="/register/tab2">tab2</router-link>
<!-- 子路由的占位符 -->
<router-view />
<div>`
}
const Tab1 = {
template: '<h3>tab1 子组件</h3>'
}
const Tab2 = {
template: '<h3>tab2 子组件</h3>'
}
// 创建路由实例对象
const router = new VueRouter({
// 所有的路由规则
routes: [
{ path: '/', redirect: '/user'},
{ path: '/user', component: User },
// children 数组表示子路由规则
{ path: '/register', component: Register, children: [
{ path: '/register/tab1', component: Tab1 },
{ path: '/register/tab2', component: Tab2 }
] }
]
})
// 创建 vm 实例对象
const vm = new Vue({
// 指定控制的区域
el: '#app',
data: {},
// 挂载路由实例对象
// router: router
router
})
</script>
</body>
</html>
6、动态路由匹配
6.1 动态匹配路由的基本用法
思考:
<!– 有如下 3 个路由链接 -->
<router-link to="/user/1">User1</router-link>
<router-link to="/user/2">User2</router-link>
<router-link to="/user/3">User3</router-link>
// 定义如下三个对应的路由规则,是否可行???
{ path: '/user/1', component: User }
{ path: '/user/2', component: User }
{ path: '/user/3', component: User }
虽然以上规则可以匹配成功,但是这样写比较麻烦。如果有100个规则,那么写起来就会非常的麻烦。
通过观察,可以发现整个路由规则中只有后续的数字是在变化的。所以这里可以通过动态路由参数的模式进行路由匹配。
var router = new VueRouter({
routes: [
// 动态路径参数 以冒号开头
{ path: '/user/:id', component: User }
]
})
const User = {
// 路由组件中通过$route.params获取路由参数
template: '<div>User {{ $route.params.id }}</div>'
}
具体代码实现如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<!-- 导入 vue 文件 -->
<script src="./lib/vue_2.5.22.js"></script>
<script src="./lib/vue-router_3.0.2.js"></script>
</head>
<body>
<!-- 被 vm 实例所控制的区域 -->
<div id="app">
<router-link to="/user/1">User1</router-link>
<router-link to="/user/2">User2</router-link>
<router-link to="/user/3">User3</router-link>
<router-link to="/register">Register</router-link>
<!-- 路由占位符 -->
<router-view></router-view>
</div>
<script>
const User = {
template: '<h1>User 组件 -- 用户id为: {{$route.params.id}}</h1>'
}
const Register = {
template: '<h1>Register 组件</h1>'
}
// 创建路由实例对象
const router = new VueRouter({
// 所有的路由规则
routes: [
{ path: '/', redirect: '/user'},
{ path: '/user/:id', component: User },
{ path: '/register', component: Register }
]
})
// 创建 vm 实例对象
const vm = new Vue({
// 指定控制的区域
el: '#app',
data: {},
// 挂载路由实例对象
// router: router
router
})
</script>
</body>
</html>
6.2 路由组件传递参数
$route
与对应路由形成高度耦合,不够灵活,所以可以使用props
将组件和路由解耦
第一种情况:
props的值为布尔类型
const router = new VueRouter({
routes: [
// 如果 props 被设置为 true,route.params 将会被设置为组件属性
{ path: '/user/:id', component: User, props: true }
]
})
const User = {
props: ['id'], // 使用 props 接收路由参数
template: '<div>用户ID:{{ id }}</div>' // 使用路由参数
}
在定义路由规则的时候,为其添加了props
属性,并将其值设置为true
.那么在组件中就可以通过props:['id']
的形式来获取对应的参数值。
具体代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<!-- 导入 vue 文件 -->
<script src="./lib/vue_2.5.22.js"></script>
<script src="./lib/vue-router_3.0.2.js"></script>
</head>
<body>
<!-- 被 vm 实例所控制的区域 -->
<div id="app">
<router-link to="/user/1">User1</router-link>
<router-link to="/user/2">User2</router-link>
<router-link to="/user/3">User3</router-link>
<router-link to="/register">Register</router-link>
<!-- 路由占位符 -->
<router-view></router-view>
</div>
<script>
const User = {
props: ['id'], //获取id的值。
template: '<h1>User 组件 -- 用户id为: {{id}}</h1>'
}
const Register = {
template: '<h1>Register 组件</h1>'
}
// 创建路由实例对象
const router = new VueRouter({
// 所有的路由规则
routes: [
{ path: '/', redirect: '/user'},
//将props设置为true.
{ path: '/user/:id', component: User, props: true },
{ path: '/register', component: Register }
]
})
// 创建 vm 实例对象
const vm = new Vue({
// 指定控制的区域
el: '#app',
data: {},
// 挂载路由实例对象
// router: router
router
})
</script>
</body>
</html>
第二种情况: props
的值为对象类型
const router = new VueRouter({
routes: [
// 如果 props 是一个对象,它会被按原样设置为组件属性
//这里相当于给组件User,通过路由的形式传递了一个对象,而这时候id在User组件中就无法获取到了。
{ path: '/user/:id', component: User, props: { uname: 'lisi', age: 12 }}
]
})
const User = {
props: ['uname', 'age'],
template: ‘<div>用户信息:{{ uname + '---' + age}}</div>'
}
具体代码实现如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<!-- 导入 vue 文件 -->
<script src="./lib/vue_2.5.22.js"></script>
<script src="./lib/vue-router_3.0.2.js"></script>
</head>
<body>
<!-- 被 vm 实例所控制的区域 -->
<div id="app">
<router-link to="/user/1">User1</router-link>
<router-link to="/user/2">User2</router-link>
<router-link to="/user/3">User3</router-link>
<router-link to="/register">Register</router-link>
<!-- 路由占位符 -->
<router-view></router-view>
</div>
<script>
const User = {
props: ['id', 'uname', 'age'],
template: '<h1>User 组件 -- 用户id为: {{id}} -- 姓名为:{{uname}} -- 年龄为:{{age}}</h1>'
}
const Register = {
template: '<h1>Register 组件</h1>'
}
// 创建路由实例对象
const router = new VueRouter({
// 所有的路由规则
routes: [
{ path: '/', redirect: '/user'},
{ path: '/user/:id', component: User, props: { uname: 'lisi', age: 20 } },
{ path: '/register', component: Register }
]
})
// 创建 vm 实例对象
const vm = new Vue({
// 指定控制的区域
el: '#app',
data: {},
// 挂载路由实例对象
// router: router
router
})
</script>
</body>
</html>
在上面的代码中,在路由规则中,通过props
向用户组件中传递了一个对象,那么在User
用户组件中可以接收到传递过来的对象。但是参数id
无法接收到。
如果要解决这个问题,可以使用props
的值为函数类型。也就是给props
传递一个函数。
第三种情况:props
的值为函数类型
const router = new VueRouter({
routes: [
// 如果 props 是一个函数,则这个函数接收 route 对象为自己的形参
//route就是参数对象。
{ path: '/user/:id',
component: User,
props: route => ({ uname: 'zs', age: 20, id: route.params.id })}
]
})
const User = {
props: ['uname', 'age', 'id'],
template: ‘<div>用户信息:{{ uname + '---' + age + '---' + id}}</div>'
}
完整代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<!-- 导入 vue 文件 -->
<script src="./lib/vue_2.5.22.js"></script>
<script src="./lib/vue-router_3.0.2.js"></script>
</head>
<body>
<!-- 被 vm 实例所控制的区域 -->
<div id="app">
<router-link to="/user/1">User1</router-link>
<router-link to="/user/2">User2</router-link>
<router-link to="/user/3">User3</router-link>
<router-link to="/register">Register</router-link>
<!-- 路由占位符 -->
<router-view></router-view>
</div>
<script>
const User = {
props: ['id', 'uname', 'age'],
template: '<h1>User 组件 -- 用户id为: {{id}} -- 姓名为:{{uname}} -- 年龄为:{{age}}</h1>'
}
const Register = {
template: '<h1>Register 组件</h1>'
}
// 创建路由实例对象
const router = new VueRouter({
// 所有的路由规则
routes: [
{ path: '/', redirect: '/user' },
{
path: '/user/:id',
component: User,
props: route => ({ uname: 'zs', age: 20, id: route.params.id })
},
{ path: '/register', component: Register }
]
})
// 创建 vm 实例对象
const vm = new Vue({
// 指定控制的区域
el: '#app',
data: {},
// 挂载路由实例对象
// router: router
router
})
</script>
</body>
</html>
7、命名路由
为了更加方便的表示路由的路径,可以给路由规则起一个别名,即为“命名路由”。
const router = new VueRouter({
routes: [
{
path: '/user/:id',
name: 'user',
component: User
}
]
})
<!--单击链接,可以跳转到名称为`user`的这个路由规则,并且通过params进行参数的传递-->
<router-link :to="{ name: 'user', params: { id: 123 }}">User</router-link>
完整代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<!-- 导入 vue 文件 -->
<script src="./lib/vue_2.5.22.js"></script>
<script src="./lib/vue-router_3.0.2.js"></script>
</head>
<body>
<!-- 被 vm 实例所控制的区域 -->
<div id="app">
<router-link to="/user/1">User1</router-link>
<router-link to="/user/2">User2</router-link>
<!--单击链接,可以跳转到名称为`user`的这个路由规则,并且通过params进行参数的传递,id一定要和路由规则中定义的参数保持一致-->
<router-link :to="{ name: 'user', params: {id: 3} }">User3</router-link>
<router-link to="/register">Register</router-link>
<!-- 路由占位符 -->
<router-view></router-view>
</div>
<script>
const User = {
props: ['id', 'uname', 'age'],
template: '<h1>User 组件 -- 用户id为: {{id}} -- 姓名为:{{uname}} -- 年龄为:{{age}}</h1>'
}
const Register = {
template: '<h1>Register 组件</h1>'
}
// 创建路由实例对象
const router = new VueRouter({
// 所有的路由规则
routes: [
{ path: '/', redirect: '/user' },
{
// 命名路由
name: 'user',
path: '/user/:id',
component: User,
props: route => ({ uname: 'zs', age: 20, id: route.params.id })
},
{ path: '/register', component: Register }
]
})
// 创建 vm 实例对象
const vm = new Vue({
// 指定控制的区域
el: '#app',
data: {},
// 挂载路由实例对象
// router: router
router
})
</script>
</body>
</html>
8、编程式导航
页面导航的两种方式
声明式导航:通过点击链接实现导航的方式,叫做声明式导航
例如:普通网页中的 <a></a>
链接 或 vue 中的 <router-link></router-link>
编程式导航:通过调用JavaScript
形式的API
实现导航的方式,叫做编程式导航
例如:普通网页中的 location.href
编程式导航基本用法
常用的编程式导航 API 如下:
this.$router.push
('hash地址')
this.$router.go(n)
const User = {
template: '<div><button @click="goRegister">跳转到注册页面</button></div>',
methods: {
goRegister: function(){
// 用编程的方式控制路由跳转
this.$router.push('/register');
}
}
}
具体吗实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<!-- 导入 vue 文件 -->
<script src="./lib/vue_2.5.22.js"></script>
<script src="./lib/vue-router_3.0.2.js"></script>
</head>
<body>
<!-- 被 vm 实例所控制的区域 -->
<div id="app">
<router-link to="/user/1">User1</router-link>
<router-link to="/user/2">User2</router-link>
<router-link :to="{ name: 'user', params: {id: 3} }">User3</router-link>
<router-link to="/register">Register</router-link>
<!-- 路由占位符 -->
<router-view></router-view>
</div>
<script>
const User = {
props: ['id', 'uname', 'age'],
template: `<div>
<h1>User 组件 -- 用户id为: {{id}} -- 姓名为:{{uname}} -- 年龄为:{{age}}</h1>
<button @click="goRegister">跳转到注册页面</button>
</div>`,
methods: {
goRegister() {
this.$router.push('/register')//编程式导航
}
},
}
const Register = {
template: `<div>
<h1>Register 组件</h1>
<button @click="goBack">后退</button>
</div>`,
methods: {
goBack() {
this.$router.go(-1)
}
}
}
// 创建路由实例对象
const router = new VueRouter({
// 所有的路由规则
routes: [
{ path: '/', redirect: '/user' },
{
// 命名路由
name: 'user',
path: '/user/:id',
component: User,
props: route => ({ uname: 'zs', age: 20, id: route.params.id })
},
{ path: '/register', component: Register }
]
})
// 创建 vm 实例对象
const vm = new Vue({
// 指定控制的区域
el: '#app',
data: {},
// 挂载路由实例对象
// router: router
router
})
</script>
</body>
</html>
router.push() 方法的参数规则
// 字符串(路径名称)
router.push('/home')
// 对象
router.push({ path: '/home' })
// 命名的路由(传递参数)
router.push({ name: '/user', params: { userId: 123 }})
// 带查询参数,变成 /register?uname=lisi
router.push({ path: '/register', query: { uname: 'lisi' }})
9、路由案例
9.1 抽离并且渲染App
根组件。
将素材中的代码修改成如下的形式:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>基于vue-router的案例</title>
<script src="./lib/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<style type="text/css">
html,
body,
#app {
margin: 0;
padding: 0px;
height: 100%;
}
.header {
height: 50px;
background-color: #545c64;
line-height: 50px;
text-align: center;
font-size: 24px;
color: #fff;
}
.footer {
height: 40px;
line-height: 40px;
background-color: #888;
position: absolute;
bottom: 0;
width: 100%;
text-align: center;
color: #fff;
}
.main {
display: flex;
position: absolute;
top: 50px;
bottom: 40px;
width: 100%;
}
.content {
flex: 1;
text-align: center;
height: 100%;
}
.left {
flex: 0 0 20%;
background-color: #545c64;
}
.left a {
color: white;
text-decoration: none;
}
.right {
margin: 5px;
}
.btns {
width: 100%;
height: 35px;
line-height: 35px;
background-color: #f5f5f5;
text-align: left;
padding-left: 10px;
box-sizing: border-box;
}
button {
height: 30px;
background-color: #ecf5ff;
border: 1px solid lightskyblue;
font-size: 12px;
padding: 0 20px;
}
.main-content {
margin-top: 10px;
}
ul {
margin: 0;
padding: 0;
list-style: none;
}
ul li {
height: 45px;
line-height: 45px;
background-color: #a0a0a0;
color: #fff;
cursor: pointer;
border-bottom: 1px solid #fff;
}
table {
width: 100%;
border-collapse: collapse;
}
td,
th {
border: 1px solid #eee;
line-height: 35px;
font-size: 12px;
}
th {
background-color: #ddd;
}
</style>
</head>
<body>
<div id="app"><router-view></router-view></div>
<script>
const App = {
template: `<div>
<!-- 头部区域 -->
<header class="header">传智后台管理系统</header>
<!-- 中间主体区域 -->
<div class="main">
<!-- 左侧菜单栏 -->
<div class="content left">
<ul>
<li>用户管理</li>
<li>权限管理</li>
<li>商品管理</li>
<li>订单管理</li>
<li>系统设置</li>
</ul>
</div>
<!-- 右侧内容区域 -->
<div class="content right"><div class="main-content">添加用户表单</div></div>
</div>
<!-- 尾部区域 -->
<footer class="footer">版权信息</footer>
</div>`,
};
//创建路由对象
const router = new VueRouter({
routes: [{ path: "/", component: App }],
});
const vm = new Vue({
el: "#app",
router,
});
</script>
</body>
</html>
在上面的代码中,我们导入了Vue
与Vue-Router
的文件。
然后将核心内容定义到App
这个组件中,同时创建了路由对象,并且指定了路由的规则。接下来将路由对象挂载到了Vue
的实例中。
同时在<div id='app'></div>
中使用router-view
定义了一个占位符。当输入的地址为/
,对应的App
组件就会在该占位符中进行展示。
9.2 将菜单改造为路由连接
将模板中的菜单修改成路由连接的形式,如下所示:
<!-- 左侧菜单栏 -->
<div class="content left">
<ul>
<li><router-link to="/users"> 用户管理</router-link></li>
<li><router-link to="/rights"> 权限管理</router-link></li>
<li><router-link to="/goods"> 商品管理</router-link></li>
<li><router-link to="/orders"> 订单管理</router-link></li>
<li><router-link to="/settings"> 系统设置</router-link></li>
</ul>
</div>
9.3 创建菜单对应组件
基本组件创建如下:
const Users = {
template: `<div>
<h3>用户管理区域</h3>
</div>`,
};
const Rights = {
template: `<div>
<h3>权限管理区域</h3>
</div>`,
};
const Goods = {
template: `<div>
<h3>商品管理区域</h3>
</div>`,
};
const Orders = {
template: `<div>
<h3>订单管理区域</h3>
</div>`,
};
const Settings = {
template: `<div>
<h3>系统设置区域</h3>
</div>`,
};
我们知道,当单击左侧的菜单时,上面定义的组件将会在右侧进行展示。
所以需要在右侧,添加一个router-view
的占位符。
<!-- 右侧内容区域 -->
<div class="content right"><div class="main-content"> <router-view /></div></div>
9.4 添加子路由规则并实现路由重定向
在上一小节中,我们已经将组件都定义好了,下面需要定义其对应的路由规则。
怎样添加对应的路由规则呢?
我们知道整个页面是App
根组件渲染出来的,而前面定义的组件,都是在App
根组件中进行渲染的,也就是作为了App
组件的子组件。
所以,为上一小节中创建的组件添加路由规则,应该是作为App
的子路由来进行添加,这样对应的组件才会在App
组件中进行渲染。
// 创建路由对象
const router = new VueRouter({
routes: [
{
path: "/",
component: App,
redirect: "/users",
children: [
{ path: "/users", component: Users },
{ path: "/rights", component: Rights },
{ path: "/goods", component: Goods },
{ path: "/orders", component: Orders },
{ path: "/settings", component: Settings },
],
},
],
});
当用户在浏览器的地址栏中输入'/'的时候,会渲染App
组件,同时会重定向到/users
,从而将Users
组件渲染出来,而Users
组件是在整个App
组件的右侧进行渲染展示。
当点击左侧的菜单时,对应的组件会在右侧进行展示。
9.5 渲染用户列表数据
这里将用户组件的内容修改成如下形式:
const Users = {
data() {
return {
userlist: [
{ id: 1, name: "张三", age: 10 },
{ id: 2, name: "李四", age: 20 },
{ id: 3, name: "王五", age: 30 },
{ id: 4, name: "赵六", age: 40 },
],
};
},
template: `<div>
<h3>用户管理区域</h3>
<table>
<thead>
<tr><th>编号</th><th>姓名</th><th>年龄</th><th>操作</th></tr>
</thead>
<tbody>
<tr v-for="item in userlist" :key="item.id">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.age}}</td>
<td>
<a href="javascript:;">详情</a>
</td>
</tr>
</tbody>
</table>
</div>`,
};
在Users
组件中定义用户数据,并且在模板中通过循环的方式将数据渲染出来。
9.6 跳转到详情页
当单击"详情"链接时,跳转到对应的详情页面。这里需要用到编程式导航的内容。
首先定义用户详情页组件
//用户详情组件
const UserInfo = {
props: ["id"],
template: `<div>
<h5>用户详情页 --- 用户Id为:{{id}}</h5>
<button @click="goback()">后退</button>
</div>`,
methods: {
goback() {
// 实现后退功能
this.$router.go(-1);
},
},
};
在该组件中通过props
方式接收传递过来的的用户编号,并且将其打印出来。
同时在该组件中添加一个后退的按钮,通过编程式导航的方式实现后退。
对应的路由规则如下:
// 创建路由对象
const router = new VueRouter({
routes: [
{
path: "/",
component: App,
redirect: "/users",
children: [
{ path: "/users", component: Users },
{ path: "/userinfo/:id", component: UserInfo, props: true },
{ path: "/rights", component: Rights },
{ path: "/goods", component: Goods },
{ path: "/orders", component: Orders },
{ path: "/settings", component: Settings },
],
},
],
});
当输入的地址为:'/userinfo/5'的形式是会渲染UserInfo
这个组件,同时将props
设置为true
,表示会传递对应的id
值。
UserInfo
这个组件也是App
组件的子组件,对应的也会在App
组件的右侧进行展示。
同时,在Users
组件中,给“详情”链接添加对应的单击事件,
const Users = {
data() {
return {
userlist: [
{ id: 1, name: "张三", age: 10 },
{ id: 2, name: "李四", age: 20 },
{ id: 3, name: "王五", age: 30 },
{ id: 4, name: "赵六", age: 40 },
],
};
},
methods: {
goDetail(id) {
console.log(id);
this.$router.push("/userinfo/" + id);
},
},
template: `<div>
<h3>用户管理区域</h3>
<table>
<thead>
<tr><th>编号</th><th>姓名</th><th>年龄</th><th>操作</th></tr>
</thead>
<tbody>
<tr v-for="item in userlist" :key="item.id">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.age}}</td>
<td>
<a href="javascript:;" @click="goDetail(item.id)">详情</a>
</td>
</tr>
</tbody>
</table>
</div>`,
};
对应goDetail
方法中,通过编程式导航跳转到用户详情页面。
完整代码案例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>基于vue-router的案例</title>
<script src="./lib/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<style type="text/css">
html,
body,
#app {
margin: 0;
padding: 0px;
height: 100%;
}
.header {
height: 50px;
background-color: #545c64;
line-height: 50px;
text-align: center;
font-size: 24px;
color: #fff;
}
.footer {
height: 40px;
line-height: 40px;
background-color: #888;
position: absolute;
bottom: 0;
width: 100%;
text-align: center;
color: #fff;
}
.main {
display: flex;
position: absolute;
top: 50px;
bottom: 40px;
width: 100%;
}
.content {
flex: 1;
text-align: center;
height: 100%;
}
.left {
flex: 0 0 20%;
background-color: #545c64;
}
.left a {
color: white;
text-decoration: none;
}
.right {
margin: 5px;
}
.btns {
width: 100%;
height: 35px;
line-height: 35px;
background-color: #f5f5f5;
text-align: left;
padding-left: 10px;
box-sizing: border-box;
}
button {
height: 30px;
background-color: #ecf5ff;
border: 1px solid lightskyblue;
font-size: 12px;
padding: 0 20px;
}
.main-content {
margin-top: 10px;
}
ul {
margin: 0;
padding: 0;
list-style: none;
}
ul li {
height: 45px;
line-height: 45px;
background-color: #a0a0a0;
color: #fff;
cursor: pointer;
border-bottom: 1px solid #fff;
}
table {
width: 100%;
border-collapse: collapse;
}
td,
th {
border: 1px solid #eee;
line-height: 35px;
font-size: 12px;
}
th {
background-color: #ddd;
}
</style>
</head>
<body>
<div id="app"><router-view></router-view></div>
<script>
const App = {
template: `<div>
<!-- 头部区域 -->
<header class="header">传智后台管理系统</header>
<!-- 中间主体区域 -->
<div class="main">
<!-- 左侧菜单栏 -->
<div class="content left">
<ul>
<li><router-link to="/users"> 用户管理</router-link></li>
<li><router-link to="/rights"> 权限管理</router-link></li>
<li><router-link to="/goods"> 商品管理</router-link></li>
<li><router-link to="/orders"> 订单管理</router-link></li>
<li><router-link to="/settings"> 系统设置</router-link></li>
</ul>
</div>
<!-- 右侧内容区域 -->
<div class="content right"><div class="main-content"> <router-view /></div></div>
</div>
<!-- 尾部区域 -->
<footer class="footer">版权信息</footer>
</div>`,
};
const Users = {
data() {
return {
userlist: [
{ id: 1, name: "张三", age: 10 },
{ id: 2, name: "李四", age: 20 },
{ id: 3, name: "王五", age: 30 },
{ id: 4, name: "赵六", age: 40 },
],
};
},
methods: {
goDetail(id) {
console.log(id);
this.$router.push("/userinfo/" + id);
},
},
template: `<div>
<h3>用户管理区域</h3>
<table>
<thead>
<tr><th>编号</th><th>姓名</th><th>年龄</th><th>操作</th></tr>
</thead>
<tbody>
<tr v-for="item in userlist" :key="item.id">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.age}}</td>
<td>
<a href="javascript:;" @click="goDetail(item.id)">详情</a>
</td>
</tr>
</tbody>
</table>
</div>`,
};
//用户详情组件
const UserInfo = {
props: ["id"],
template: `<div>
<h5>用户详情页 --- 用户Id为:{{id}}</h5>
<button @click="goback()">后退</button>
</div>`,
methods: {
goback() {
// 实现后退功能
this.$router.go(-1);
},
},
};
const Rights = {
template: `<div>
<h3>权限管理区域</h3>
</div>`,
};
const Goods = {
template: `<div>
<h3>商品管理区域</h3>
</div>`,
};
const Orders = {
template: `<div>
<h3>订单管理区域</h3>
</div>`,
};
const Settings = {
template: `<div>
<h3>系统设置区域</h3>
</div>`,
};
// 创建路由对象
const router = new VueRouter({
routes: [
{
path: "/",
component: App,
redirect: "/users",
children: [
{ path: "/users", component: Users },
{ path: "/userinfo/:id", component: UserInfo, props: true },
{ path: "/rights", component: Rights },
{ path: "/goods", component: Goods },
{ path: "/orders", component: Orders },
{ path: "/settings", component: Settings },
],
},
],
});
const vm = new Vue({
el: "#app",
router,
});
</script>
</body>
</html>
10、路由守卫
Vue-router
中的路由守卫,主要是对其内容进行保护,如果没有对应的权限,则不允许访问。
我们首先来看一下全局守卫,也就是所有的路由都会经过全局守卫来进行检测。
//实现全局守卫
router.beforeEach((to, from, next) => {
//to:去哪个页面,from来自哪个页面,next继续执行.
//判断哪个路由需要进行守卫,这里可以通过元数据方式
if (to.meta.auth) {
if (window.isLogin) {
next();
} else {
next("/login?redirect=" + to.fullPath);
}
} else {
next();
}
});
在上面的代码中,创建了路由守卫,但是需要判断的是需要对哪个路由进行守卫,这里就是通过元数据来进行判断的。如果所跳转到的路由有元数据,并且对应的auth
属性为true
表明是需要进行守卫的,那么下面就需要校验用户是否登录,这里是通过判断否window.isLogin
的值是否为true
来进行判断的(这里简化了操作,实际应用中应该存储到sessionStorage
),如果条件成立则表明用户登录,就继续访问用户希望访问到的页面,否则跳转到登录页面,而且将用户希望访问的页面地址也传递到了登录页面,这样用户登录成功后,可以直接跳转到要访问的页面。
如果没有元数据,则继续访问用户要访问的页面。
// 创建路由对象
const router = new VueRouter({
routes: [
{ path: "/login", component: Login },
{
path: "/",
component: App,
redirect: "/users",
children: [
{
path: "/users",
component: Users,
meta: {
auth: true,
},
},
{ path: "/userinfo/:id", component: UserInfo, props: true },
{ path: "/rights", component: Rights },
{ path: "/goods", component: Goods },
{ path: "/orders", component: Orders },
{ path: "/settings", component: Settings },
],
},
],
});
在上面的代码中,给/users
路由添加了元数据。
登录组件创建如下:
const Login = {
data() {
return {
isLogin: window.isLogin,
};
},
template: `<div>
<button @click="login" v-if="!isLogin">登录</button>
<button @click="logout" v-else>注销</button>
</div>`,
methods: {
login() {
window.isLogin = true;
this.$router.push(this.$route.query.redirect);
},
logout() {
this.isLogin = window.isLogin = false;
},
},
};
当单击登录按钮后,进行将window.isLogin
设置为true
, 并且进行跳转。
全部代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>基于vue-router的案例</title>
<script src="./lib/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<style type="text/css">
html,
body,
#app {
margin: 0;
padding: 0px;
height: 100%;
}
.header {
height: 50px;
background-color: #545c64;
line-height: 50px;
text-align: center;
font-size: 24px;
color: #fff;
}
.footer {
height: 40px;
line-height: 40px;
background-color: #888;
position: absolute;
bottom: 0;
width: 100%;
text-align: center;
color: #fff;
}
.main {
display: flex;
position: absolute;
top: 50px;
bottom: 40px;
width: 100%;
}
.content {
flex: 1;
text-align: center;
height: 100%;
}
.left {
flex: 0 0 20%;
background-color: #545c64;
}
.left a {
color: white;
text-decoration: none;
}
.right {
margin: 5px;
}
.btns {
width: 100%;
height: 35px;
line-height: 35px;
background-color: #f5f5f5;
text-align: left;
padding-left: 10px;
box-sizing: border-box;
}
button {
height: 30px;
background-color: #ecf5ff;
border: 1px solid lightskyblue;
font-size: 12px;
padding: 0 20px;
}
.main-content {
margin-top: 10px;
}
ul {
margin: 0;
padding: 0;
list-style: none;
}
ul li {
height: 45px;
line-height: 45px;
background-color: #a0a0a0;
color: #fff;
cursor: pointer;
border-bottom: 1px solid #fff;
}
table {
width: 100%;
border-collapse: collapse;
}
td,
th {
border: 1px solid #eee;
line-height: 35px;
font-size: 12px;
}
th {
background-color: #ddd;
}
</style>
</head>
<body>
<div id="app"><router-view></router-view></div>
<script>
const App = {
template: `<div>
<!-- 头部区域 -->
<header class="header">传智后台管理系统</header>
<!-- 中间主体区域 -->
<div class="main">
<!-- 左侧菜单栏 -->
<div class="content left">
<ul>
<li><router-link to="/users"> 用户管理</router-link></li>
<li><router-link to="/rights"> 权限管理</router-link></li>
<li><router-link to="/goods"> 商品管理</router-link></li>
<li><router-link to="/orders"> 订单管理</router-link></li>
<li><router-link to="/settings"> 系统设置</router-link></li>
</ul>
</div>
<!-- 右侧内容区域 -->
<div class="content right"><div class="main-content"> <router-view /></div></div>
</div>
<!-- 尾部区域 -->
<footer class="footer">版权信息</footer>
</div>`,
};
const Users = {
data() {
return {
userlist: [
{ id: 1, name: "张三", age: 10 },
{ id: 2, name: "李四", age: 20 },
{ id: 3, name: "王五", age: 30 },
{ id: 4, name: "赵六", age: 40 },
],
};
},
methods: {
goDetail(id) {
console.log(id);
this.$router.push("/userinfo/" + id);
},
},
template: `<div>
<h3>用户管理区域</h3>
<table>
<thead>
<tr><th>编号</th><th>姓名</th><th>年龄</th><th>操作</th></tr>
</thead>
<tbody>
<tr v-for="item in userlist" :key="item.id">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.age}}</td>
<td>
<a href="javascript:;" @click="goDetail(item.id)">详情</a>
</td>
</tr>
</tbody>
</table>
</div>`,
};
//用户详情组件
const UserInfo = {
props: ["id"],
template: `<div>
<h5>用户详情页 --- 用户Id为:{{id}}</h5>
<button @click="goback()">后退</button>
</div>`,
methods: {
goback() {
// 实现后退功能
this.$router.go(-1);
},
},
};
const Rights = {
template: `<div>
<h3>权限管理区域</h3>
</div>`,
};
const Goods = {
template: `<div>
<h3>商品管理区域</h3>
</div>`,
};
const Orders = {
template: `<div>
<h3>订单管理区域</h3>
</div>`,
};
const Settings = {
template: `<div>
<h3>系统设置区域</h3>
</div>`,
};
const Login = {
data() {
return {
isLogin: window.isLogin,
};
},
template: `<div>
<button @click="login" v-if="!isLogin">登录</button>
<button @click="logout" v-else>注销</button>
</div>`,
methods: {
login() {
window.isLogin = true;
this.$router.push(this.$route.query.redirect);
},
logout() {
this.isLogin = window.isLogin = false;
},
},
};
// 创建路由对象
const router = new VueRouter({
routes: [
{ path: "/login", component: Login },
{
path: "/",
component: App,
redirect: "/users",
children: [
{
path: "/users",
component: Users,
meta: {
auth: true,
},
},
{ path: "/userinfo/:id", component: UserInfo, props: true },
{ path: "/rights", component: Rights },
{ path: "/goods", component: Goods },
{ path: "/orders", component: Orders },
{ path: "/settings", component: Settings },
],
},
],
});
//实现全局守卫
router.beforeEach((to, from, next) => {
//to:去哪个页面,from来自哪个页面,next继续执行.
//判断哪个路由需要进行守卫,这里可以通过元数据方式
if (to.meta.auth) {
if (window.isLogin) {
next();
} else {
next("/login?redirect=" + to.fullPath);
}
} else {
next();
}
});
const vm = new Vue({
el: "#app",
router,
});
</script>
</body>
</html>
以上是全局守卫,对所有的路由都起作用。
但是,如果项目比较简单,路由规则定义的比较少,可以将守卫定位到某个路由规则内。这就是路由独享守卫
// 创建路由对象
const router = new VueRouter({
routes: [
{ path: "/login", component: Login },
{
path: "/",
component: App,
redirect: "/users",
children: [
{
path: "/users",
component: Users,
meta: {
auth: true,
},
beforeEnter(to, from, next) {
if (window.isLogin) {
next();
} else {
next("/login?redirect=" + to.fullPath);
}
},
},
{ path: "/userinfo/:id", component: UserInfo, props: true },
{ path: "/rights", component: Rights },
{ path: "/goods", component: Goods },
{ path: "/orders", component: Orders },
{ path: "/settings", component: Settings },
],
},
],
});
在上面的代码中,给/users
这个路由守卫,注意这里的方法名为beforeEnter
.同时,这里将守卫定义在/users
路由规则内,所以不需要对元数据进行判断,只需要判断用户是否登录就可以了。(注意:在进行以上测试时,需要将全局守卫的代码注释掉)
组件内守卫
可以在路由组件内直接定义以下路由导航守卫。
beforeRouteEnter
beforeRouteUpdate
beforeRouteLeave
将如下的代码直接添加到组件内。
const Users = {
data() {
return {
userlist: [
{ id: 1, name: "张三", age: 10 },
{ id: 2, name: "李四", age: 20 },
{ id: 3, name: "王五", age: 30 },
{ id: 4, name: "赵六", age: 40 },
],
};
},
methods: {
goDetail(id) {
console.log(id);
this.$router.push("/userinfo/" + id);
},
},
template: `<div>
<h3>用户管理区域</h3>
<table>
<thead>
<tr><th>编号</th><th>姓名</th><th>年龄</th><th>操作</th></tr>
</thead>
<tbody>
<tr v-for="item in userlist" :key="item.id">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.age}}</td>
<td>
<a href="javascript:;" @click="goDetail(item.id)">详情</a>
</td>
</tr>
</tbody>
</table>
</div>`,
beforeRouteEnter(to, from, next) {
if (window.isLogin) {
next();
} else {
next("/login?redirect=" + to.fullPath);
}
},
};
在上面的代码中,直接将路由守卫对应的方法添加到了组件中。
注意:在测试之前将路由规则中定义的路由守卫的代码注释掉。
11、addRoutes动态路由添加
在前面的案例中,我们都是将路由定义好,然后通过路由守卫来判断,某个用户是否登录,从而决定能否访问某个路由规则对应的组件内容。
但是,如果某些路由规则只能用户登录以后才能够访问,那么我们也可以不用提前定义好,而是在登录后,通过addRoutes
方法为其动态的添加。
首先这里需要,还需要全局的路由守卫来进行校验判断,只不过这里全局路由守卫的逻辑发生了变化。
router.beforeEach((to, from, next) => {
//to:去哪个页面,from来自哪个页面,next继续执行.
if (window.isLogin) {
//用户已经登录
if (to.path === "/login") {
// 用户已经登录了,但是又访问登录页面,这里直接跳转到用户列表页面
next("/");
} else {
//用户已经登录,并且访问其它页面,则运行访问
next();
}
} else {
//用户没有登录,并且访问的就是登录页,则运行访问登录页
if (to.path === "/login") {
next();
} else {
//用户没有登录,访问其它页面,则跳转到登录页面。
next("/login?redirect=" + to.fullPath);
}
}
});
下面对登录组件进行修改
const Login = {
data() {
return {
isLogin: window.isLogin,
};
},
template: `<div>
<button @click="login" v-if="!isLogin">登录</button>
<button @click="logout" v-else>注销</button>
</div>`,
methods: {
login() {
window.isLogin = true;
if (this.$route.query.redirect) {
//动态添加路由:
this.$router.addRoutes([
{
path: "/",
component: App,
redirect: "/users",
children: [
{
path: "/users",
component: Users,
meta: {
auth: true,
},
// beforeEnter(to, from, next) {
// if (window.isLogin) {
// next();
// } else {
// next("/login?redirect=" + to.fullPath);
// }
// },
},
{ path: "/userinfo/:id", component: UserInfo, props: true },
{ path: "/rights", component: Rights },
{ path: "/goods", component: Goods },
{ path: "/orders", component: Orders },
{ path: "/settings", component: Settings },
],
},
]);
this.$router.push(this.$route.query.redirect);
} else {
this.$router.push("/");
}
},
logout() {
this.isLogin = window.isLogin = false;
},
},
};
在登录成功后,通过addRoutes
方法动态的添加路由规则,也就是所添加的路由规则只能是在登录以后才能够访问,所以全局守卫的判断条件发生了变化,不在判断是否有元数据,而只是判断是否登录。如果登录了,想访问上面的路由规则,则运行访问,如果没有登录则不允许访问。
注意:对应的原有的路由规则应该注释掉。
完整代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>基于vue-router的案例</title>
<script src="./lib/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<style type="text/css">
html,
body,
#app {
margin: 0;
padding: 0px;
height: 100%;
}
.header {
height: 50px;
background-color: #545c64;
line-height: 50px;
text-align: center;
font-size: 24px;
color: #fff;
}
.footer {
height: 40px;
line-height: 40px;
background-color: #888;
position: absolute;
bottom: 0;
width: 100%;
text-align: center;
color: #fff;
}
.main {
display: flex;
position: absolute;
top: 50px;
bottom: 40px;
width: 100%;
}
.content {
flex: 1;
text-align: center;
height: 100%;
}
.left {
flex: 0 0 20%;
background-color: #545c64;
}
.left a {
color: white;
text-decoration: none;
}
.right {
margin: 5px;
}
.btns {
width: 100%;
height: 35px;
line-height: 35px;
background-color: #f5f5f5;
text-align: left;
padding-left: 10px;
box-sizing: border-box;
}
button {
height: 30px;
background-color: #ecf5ff;
border: 1px solid lightskyblue;
font-size: 12px;
padding: 0 20px;
}
.main-content {
margin-top: 10px;
}
ul {
margin: 0;
padding: 0;
list-style: none;
}
ul li {
height: 45px;
line-height: 45px;
background-color: #a0a0a0;
color: #fff;
cursor: pointer;
border-bottom: 1px solid #fff;
}
table {
width: 100%;
border-collapse: collapse;
}
td,
th {
border: 1px solid #eee;
line-height: 35px;
font-size: 12px;
}
th {
background-color: #ddd;
}
</style>
</head>
<body>
<div id="app"><router-view></router-view></div>
<script>
const App = {
template: `<div>
<!-- 头部区域 -->
<header class="header">传智后台管理系统</header>
<!-- 中间主体区域 -->
<div class="main">
<!-- 左侧菜单栏 -->
<div class="content left">
<ul>
<li><router-link to="/users"> 用户管理</router-link></li>
<li><router-link to="/rights"> 权限管理</router-link></li>
<li><router-link to="/goods"> 商品管理</router-link></li>
<li><router-link to="/orders"> 订单管理</router-link></li>
<li><router-link to="/settings"> 系统设置</router-link></li>
</ul>
</div>
<!-- 右侧内容区域 -->
<div class="content right"><div class="main-content"> <router-view /></div></div>
</div>
<!-- 尾部区域 -->
<footer class="footer">版权信息</footer>
</div>`,
};
const Users = {
data() {
return {
userlist: [
{ id: 1, name: "张三", age: 10 },
{ id: 2, name: "李四", age: 20 },
{ id: 3, name: "王五", age: 30 },
{ id: 4, name: "赵六", age: 40 },
],
};
},
methods: {
goDetail(id) {
console.log(id);
this.$router.push("/userinfo/" + id);
},
},
template: `<div>
<h3>用户管理区域</h3>
<table>
<thead>
<tr><th>编号</th><th>姓名</th><th>年龄</th><th>操作</th></tr>
</thead>
<tbody>
<tr v-for="item in userlist" :key="item.id">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.age}}</td>
<td>
<a href="javascript:;" @click="goDetail(item.id)">详情</a>
</td>
</tr>
</tbody>
</table>
</div>`,
// beforeRouteEnter(to, from, next) {
// if (window.isLogin) {
// next();
// } else {
// next("/login?redirect=" + to.fullPath);
// }
// },
};
//用户详情组件
const UserInfo = {
props: ["id"],
template: `<div>
<h5>用户详情页 --- 用户Id为:{{id}}</h5>
<button @click="goback()">后退</button>
</div>`,
methods: {
goback() {
// 实现后退功能
this.$router.go(-1);
},
},
};
const Rights = {
template: `<div>
<h3>权限管理区域</h3>
</div>`,
};
const Goods = {
template: `<div>
<h3>商品管理区域</h3>
</div>`,
};
const Orders = {
template: `<div>
<h3>订单管理区域</h3>
</div>`,
};
const Settings = {
template: `<div>
<h3>系统设置区域</h3>
</div>`,
};
const Login = {
data() {
return {
isLogin: window.isLogin,
};
},
template: `<div>
<button @click="login" v-if="!isLogin">登录</button>
<button @click="logout" v-else>注销</button>
</div>`,
methods: {
login() {
window.isLogin = true;
if (this.$route.query.redirect) {
//动态添加路由:
this.$router.addRoutes([
{
path: "/",
component: App,
redirect: "/users",
children: [
{
path: "/users",
component: Users,
meta: {
auth: true,
},
// beforeEnter(to, from, next) {
// if (window.isLogin) {
// next();
// } else {
// next("/login?redirect=" + to.fullPath);
// }
// },
},
{ path: "/userinfo/:id", component: UserInfo, props: true },
{ path: "/rights", component: Rights },
{ path: "/goods", component: Goods },
{ path: "/orders", component: Orders },
{ path: "/settings", component: Settings },
],
},
]);
this.$router.push(this.$route.query.redirect);
} else {
this.$router.push("/");
}
},
logout() {
this.isLogin = window.isLogin = false;
},
},
};
// 创建路由对象
const router = new VueRouter({
routes: [
{ path: "/login", component: Login },
// {
// path: "/",
// component: App,
// redirect: "/users",
// children: [
// {
// path: "/users",
// component: Users,
// meta: {
// auth: true,
// },
// // beforeEnter(to, from, next) {
// // if (window.isLogin) {
// // next();
// // } else {
// // next("/login?redirect=" + to.fullPath);
// // }
// // },
// },
// { path: "/userinfo/:id", component: UserInfo, props: true },
// { path: "/rights", component: Rights },
// { path: "/goods", component: Goods },
// { path: "/orders", component: Orders },
// { path: "/settings", component: Settings },
// ],
// },
],
});
//实现全局守卫
// router.beforeEach((to, from, next) => {
// //to:去哪个页面,from来自哪个页面,next继续执行.
// //判断哪个路由需要进行守卫,这里可以通过元数据方式
// if (to.meta.auth) {
// if (window.isLogin) {
// next();
// } else {
// next("/login?redirect=" + to.fullPath);
// }
// } else {
// next();
// }
// });
router.beforeEach((to, from, next) => {
//to:去哪个页面,from来自哪个页面,next继续执行.
if (window.isLogin) {
//用户已经登录
if (to.path === "/login") {
// 用户已经登录了,但是又访问登录页面,这里直接跳转到用户列表页面
next("/");
} else {
//用户已经登录,并且访问其它页面,则运行访问
next();
}
} else {
//用户没有登录,并且访问的就是登录页,则运行访问登录页
if (to.path === "/login") {
next();
} else {
//用户没有登录,访问其它页面,则跳转到登录页面。
next("/login?redirect=" + to.fullPath);
}
}
});
const vm = new Vue({
el: "#app",
router,
});
</script>
</body>
</html>
12、路由组件缓存
利用keepalive
做组件缓存,保留组件状态,提高执行效率。
<keep-alive include="home">
<router-view></router-view>
</keep-alive>
使用include
或者exclude
时要给组件设置name
(这个是组件的名称,组件的名称通过给组件添加name
属性来进行设置)
当我们进行路由切换的时候,对应的组件会被重新创建,同时数据也会不断的重新加载。
如果数据没有变化,就没有必要每次都重新发送异步请求加载数据
现在,在App
组件中添加keep-alive
因为切换的组件都是在该router-view
中进行展示。
<!-- 右侧内容区域 -->
<div class="content right"><div class="main-content">
<keep-alive>
<router-view />
</keep-alive>
</div></div>
</div>
下面可以进行验证。
const Rights = {
template: `<div>
<h3>权限管理区域</h3>
</div>`,
created() {
console.log(new Date());
},
};
在Rights
组件中,添加了created
方法,该方法中输出日期时间,但是我们不断的切换,发现并不是每次都打印日期时间内容。
当然,以上keep-alive
的使用方式,是将所有的组件都缓存了,如果只想缓存某个组件,可以采用如下的方式
<!-- 右侧内容区域 -->
<div class="content right"><div class="main-content">
<keep-alive include='goods'>
<router-view />
</keep-alive>
</div></div>
</div>
在上面的代码中,通过include
添加了需要缓存的组件的名称,如果有多个在include
中可以继续添加,每个组件名称之间用逗号分隔。
以上的含义就是只有goods
组件需要被缓存(goods
是组件的name
值)
const Goods = {
name: "goods",
template: `<div>
<h3>商品管理区域</h3>
</div>`,
created() {
console.log(new Date());
},
};
exclude
表示的就是除了指定的组件以外(也是组件的name
),其它组件都进行缓存。
应用场景
如果未使用keep-alive组件,则在页面回退时仍然会重新渲染页面,触发created钩子,使用体验不好。 在以下场景中使用keep-alive组件会显著提高用户体验,菜单存在多级关系,多见于列表页+详情页的场景如:
- 商品列表页点击商品跳转到商品详情,返回后仍显示原有信息
- 订单列表跳转到订单详情,返回,等等场景。
生命周期:
activated
和deactivated
会在keep-alive
内所有嵌套的组件中触发
如:B页面是缓存页面
当A页面跳到B页面时,B页面的生命周期:activated(可在此时更新数据)
B页面跳出时,触发deactivated
B页面自身刷新时,会触发created-mouted-activated
13、Hash模式与History模式
13.1 Hash模式与History模式区别
前端路由中,不管是什么实现模式,都是客户端的一种实现方式,也就是当路径发生变化的时候,是不会向服务器发送请求的。
如果需要向服务器发送请求,需要用到ajax
方式。
两种模式的区别
首先是表现形式的区别
Hash
模式
https://www.baidu.com/#/showlist?id=22256
hash
模式中路径带有#
, #
后面的内容作为路由地址。可以通过问号携带参数。
当然这种模式相对来说比较丑,路径中带有与数据无关的符号,例如#
与?
History
模式
https://www.baidu.com/showlist/22256
History
模式是一个正常的路径的模式,如果要想实现这种模式,还需要服务端的相应支持。
下面再来看一下两者原理上的区别。
Hash
模式是基于锚点,以及onhashchange
事件。
通过锚点的值作为路由地址,当地址发生变化后触发onhashchange
事件。
History
模式是基于HTML5
中的History API
也就是如下两个方法
history.pushState( )
IE10
以后才支持
history.replaceState( )
13.2 History
模式的使用
History
模式需要服务器的支持,为什么呢?
因为在单页面的应用中,只有一个页面,也就是index.html
这个页面,服务端不存在http://www.test.com/login
这样的地址,也就说如果刷新浏览器,
请求服务器,是找不到/login
这个页面的,所以会出现404
的错误。(在传统的开发模式下,输入以上的地址,会返回login
这个页面,而在单页面应用中,只有一个页面为index.html
)
所以说,在服务端应该除了静态资源外都返回单页应用的index.html
下面我们开始history
模式来演示一下对应的问题。
首先添加一个针对404组件的处理
首先在菜单栏中添加一个链接:
<!-- 左侧菜单栏 -->
<div class="content left">
<ul>
<li><router-link to="/users"> 用户管理</router-link></li>
<li><router-link to="/rights"> 权限管理</router-link></li>
<li><router-link to="/goods"> 商品管理</router-link></li>
<li><router-link to="/orders"> 订单管理</router-link></li>
<li><router-link to="/settings"> 系统设置</router-link></li>
<li><router-link to="/about"> 关于</router-link></li>
</ul>
</div>
这里我们添加了一个“关于”的链接,但是我们没有为其定义相应的组件,所以这里需要处理404的情况。
const NotFound = {
template: `<div>
你访问的页面不存在!!
</div>`,
};
在程序中添加了一个针对404的组件。
const router = new VueRouter({
mode: "history",
const router = new VueRouter({
mode: "history",
routes: [
{ path: "/login", component: Login },
{ path: "*", component: NotFound },
{
path: "/",
component: App,
redirect: "/users",
children: [
{
path: "/users",
component: Users,
meta: {
auth: true,
},
// beforeEnter(to, from, next) {
// if (window.isLogin) {
// next();
// } else {
// next("/login?redirect=" + to.fullPath);
// }
// },
},
{ path: "/userinfo/:id", component: UserInfo, props: true },
{ path: "/rights", component: Rights },
{ path: "/goods", component: Goods },
{ path: "/orders", component: Orders },
{ path: "/settings", component: Settings },
],
},
],
});
在上面的代码中,指定了处理404的路由规则,同时将路由的模式修改成了history
模式。同时,启用这里启用了其它的组件的路由规则配置,也就是不在login
方法中使用addRoutes
方法来动态添加路由规则了。
login
方法修改成如下形式:
login() {
// window.isLogin = true;
window.sessionStorage.setItem("isLogin", true);
if (this.$route.query.redirect) {
// //动态添加路由:
// this.$router.addRoutes([
// {
// path: "/",
// component: App,
// redirect: "/users",
// children: [
// {
// path: "/users",
// component: Users,
// meta: {
// auth: true,
// },
// // beforeEnter(to, from, next) {
// // if (window.isLogin) {
// // next();
// // } else {
// // next("/login?redirect=" + to.fullPath);
// // }
// // },
// },
// { path: "/userinfo/:id", component: UserInfo, props: true },
// { path: "/rights", component: Rights },
// { path: "/goods", component: Goods },
// { path: "/orders", component: Orders },
// { path: "/settings", component: Settings },
// ],
// },
// ]);
this.$router.push(this.$route.query.redirect);
} else {
this.$router.push("/");
}
}
现在已经将前端vue
中的代码修改完毕了,下面我们要将页面的内容部署到node.js
服务器中。
而且上面的代码中,我们使用了sessionStorage
来保存登录用户的信息,不在使用window
下的isLogin
对应的data
内容下的代码也要修改:
const Login = {
data() {
return {
isLogin: window.sessionStorage.getItem("isLogin"),
};
},
路由守卫中的代码进行如下修改:
jsrouter.beforeEach((to, from, next) => {
//to:去哪个页面,from来自哪个页面,next继续执行.
if (window.sessionStorage.getItem("isLogin")) {
//用户已经登录
if (to.path === "/login") {
// 用户已经登录了,但是又访问登录页面,这里直接跳转到用户列表页面
next("/");
} else {
//用户已经登录,并且访问其它页面,则运行访问
next();
}
} else {
//用户没有登录,并且访问的就是登录页,则运行访问登录页
if (to.path === "/login") {
next();
} else {
//用户没有登录,访问其它页面,则跳转到登录页面。
next("/login?redirect=" + to.fullPath);
}
}
});
在上面的代码中,我们也是通过sessionStorage
来获取登录信息。
index.html
完整代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>基于vue-router的案例</title>
<script src="./lib/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>
<body>
<div id="app"><router-view></router-view></div>
<script>
const App = {
template: `<div>
<!-- 头部区域 -->
<header class="header">传智后台管理系统</header>
<!-- 中间主体区域 -->
<div class="main">
<!-- 左侧菜单栏 -->
<div class="content left">
<ul>
<li><router-link to="/users"> 用户管理</router-link></li>
<li><router-link to="/rights"> 权限管理</router-link></li>
<li><router-link to="/goods"> 商品管理</router-link></li>
<li><router-link to="/orders"> 订单管理</router-link></li>
<li><router-link to="/settings"> 系统设置</router-link></li>
<li><router-link to="/about"> 关于</router-link></li>
</ul>
</div>
<!-- 右侧内容区域 -->
<div class="content right"><div class="main-content">
<keep-alive include='goods'>
<router-view />
</keep-alive>
</div></div>
</div>
<!-- 尾部区域 -->
<footer class="footer">版权信息</footer>
</div>`,
};
const Users = {
data() {
return {
userlist: [
{ id: 1, name: "张三", age: 10 },
{ id: 2, name: "李四", age: 20 },
{ id: 3, name: "王五", age: 30 },
{ id: 4, name: "赵六", age: 40 },
],
};
},
methods: {
goDetail(id) {
console.log(id);
this.$router.push("/userinfo/" + id);
},
},
template: `<div>
<h3>用户管理区域</h3>
<table>
<thead>
<tr><th>编号</th><th>姓名</th><th>年龄</th><th>操作</th></tr>
</thead>
<tbody>
<tr v-for="item in userlist" :key="item.id">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.age}}</td>
<td>
<a href="javascript:;" @click="goDetail(item.id)">详情</a>
</td>
</tr>
</tbody>
</table>
</div>`,
// beforeRouteEnter(to, from, next) {
// if (window.isLogin) {
// next();
// } else {
// next("/login?redirect=" + to.fullPath);
// }
// },
};
//用户详情组件
const UserInfo = {
props: ["id"],
template: `<div>
<h5>用户详情页 --- 用户Id为:{{id}}</h5>
<button @click="goback()">后退</button>
</div>`,
methods: {
goback() {
// 实现后退功能
this.$router.go(-1);
},
},
};
const Rights = {
template: `<div>
<h3>权限管理区域</h3>
</div>`,
};
const Goods = {
name: "goods",
template: `<div>
<h3>商品管理区域</h3>
</div>`,
created() {
console.log(new Date());
},
};
const Orders = {
template: `<div>
<h3>订单管理区域</h3>
</div>`,
};
const Settings = {
template: `<div>
<h3>系统设置区域</h3>
</div>`,
};
const NotFound = {
template: `<div>
你访问的页面不存在!!
</div>`,
};
const Login = {
data() {
return {
isLogin: window.sessionStorage.getItem("isLogin"),
};
},
template: `<div>
<button @click="login" v-if="!isLogin">登录</button>
<button @click="logout" v-else>注销</button>
</div>`,
methods: {
login() {
// window.isLogin = true;
window.sessionStorage.setItem("isLogin", true);
if (this.$route.query.redirect) {
// //动态添加路由:
// this.$router.addRoutes([
// {
// path: "/",
// component: App,
// redirect: "/users",
// children: [
// {
// path: "/users",
// component: Users,
// meta: {
// auth: true,
// },
// // beforeEnter(to, from, next) {
// // if (window.isLogin) {
// // next();
// // } else {
// // next("/login?redirect=" + to.fullPath);
// // }
// // },
// },
// { path: "/userinfo/:id", component: UserInfo, props: true },
// { path: "/rights", component: Rights },
// { path: "/goods", component: Goods },
// { path: "/orders", component: Orders },
// { path: "/settings", component: Settings },
// ],
// },
// ]);
this.$router.push(this.$route.query.redirect);
} else {
this.$router.push("/");
}
},
logout() {
this.isLogin = window.isLogin = false;
},
},
};
// 创建路由对象
const router = new VueRouter({
mode: "history",
routes: [
{ path: "/login", component: Login },
{ path: "*", component: NotFound },
{
path: "/",
component: App,
redirect: "/users",
children: [
{
path: "/users",
component: Users,
meta: {
auth: true,
},
// beforeEnter(to, from, next) {
// if (window.isLogin) {
// next();
// } else {
// next("/login?redirect=" + to.fullPath);
// }
// },
},
{ path: "/userinfo/:id", component: UserInfo, props: true },
{ path: "/rights", component: Rights },
{ path: "/goods", component: Goods },
{ path: "/orders", component: Orders },
{ path: "/settings", component: Settings },
],
},
],
});
//实现全局守卫
// router.beforeEach((to, from, next) => {
// //to:去哪个页面,from来自哪个页面,next继续执行.
// //判断哪个路由需要进行守卫,这里可以通过元数据方式
// if (to.meta.auth) {
// if (window.isLogin) {
// next();
// } else {
// next("/login?redirect=" + to.fullPath);
// }
// } else {
// next();
// }
// });
router.beforeEach((to, from, next) => {
//to:去哪个页面,from来自哪个页面,next继续执行.
if (window.sessionStorage.getItem("isLogin")) {
//用户已经登录
if (to.path === "/login") {
// 用户已经登录了,但是又访问登录页面,这里直接跳转到用户列表页面
next("/");
} else {
//用户已经登录,并且访问其它页面,则运行访问
next();
}
} else {
//用户没有登录,并且访问的就是登录页,则运行访问登录页
if (to.path === "/login") {
next();
} else {
//用户没有登录,访问其它页面,则跳转到登录页面。
next("/login?redirect=" + to.fullPath);
}
}
});
const vm = new Vue({
el: "#app",
router,
});
</script>
</body>
</html>
当然,项目的目录结构做了一定的调整,如下图所示:
在
web
目录下面,存放的是index.html
,在webserver
目录下面存放的是node
代码。
下面看一下具体的node
代码的实现。
app.js文件中的代码如下:
const path = require("path");
//导入处理history模式的模块
const history = require("connect-history-api-fallback");
const express = require("express");
const app = express();
//注册处理history模式的中间件
// app.use(history())
//处理静态资源的中间件,处理web目录下的index.html
app.use(express.static(path.join(__dirname, "../web")));
app.listen(3000, () => {
console.log("服务器开启");
});
connect-history-api-fallback
模块的安装如下(注意在上面的代码中还没有使用该模块)
npm install --save connect-history-api-fallback
下面还需要安装express
npm install express
启动服务
node app.js
现在在地址栏中输入:http://localhost:3000
就可以访问网站了。
并且当我们去单击左侧的菜单的时候,可以实现页面的切换,同时单击“关于”的时候,会出现NotFound
组件中的内容。
经过测试发现好像没有什么问题,那这是什么原因呢?你想一下当我们单击左侧菜单的时候,路由是怎样工作的呢?
因为现在我们开启了路由的history
模式,而该模式是通过HTML5
中的history
中的api
来完成路由的操作的,也就是当我们单击菜单的时候,是通过history.pushState( )
方法来修改地址栏中的地址,实现组件的切换,而且还会把地址保存的历史记录中(也就是可以单击浏览器中后退按钮,实现后退等操作),但是它并不会向服务器发送请求。
所以说现在整个操作都是在客户端完成的。
但是,当我刷新了浏览器以后,会出现怎样的情况呢?
上图的含义就是,当单击浏览器中的刷新按钮的时候,会向服务器发送请求,要求
node
服务器处理这个地址,但是服务器并没有处理该地址,所以服务器会返回404
以上就是如果vue-router
开启了history
模式后,出现的问题。
下面解决这个问题,在服务端启用connect-history-api-fallback
模块就可以了,如下代码所示:
const path = require("path");
//导入处理history模式的模块
const history = require("connect-history-api-fallback");
const express = require("express");
const app = express();
//注册处理history模式的中间件
app.use(history());
//处理静态资源的中间件
app.use(express.static(path.join(__dirname, "../web")));
app.listen(3000, () => {
console.log("服务器开启");
});
服务端的代码做了修改以后,一定要服务端重新启动node app.js
然后经过测试以后发现没有问题了。
那么现在你考虑一下,具体的工作方式是什么?
当我们在服务端开启对history
模式的支持以后,我们刷新浏览器,会想服务器发送请求,例如:http://localhost:3000/orders
服务器接收该请求,那么用于服务器开启了history
模式,然后服务器会检查,根据该请求所访问的页面是不存在的,所以会将单页面应用的index.html
返回给浏览器。浏览器接收index.html
页面后,会判断路由地址,发现地址为orders
,所以会加载该地址对应的组件内容。
13.3 在Nginx服务器中配置History
模式
代理服务器
代理服务器:一般是指局域网内部的机器通过代理服务器发送请求到互联网上的服务器,代理服务器一般作用在客户端。应用比如:GoAgent,翻墙神器.
反向代理服务器
**反向代理服务器:**在服务器端接受客户端的请求,然后把请求分发给具体的服务器进行处理,然后再将服务器的响应结果反馈给客户端。Nginx就是其中的一种反向代理服务器软件。
Nginx简介
Nginx ("engine x") ,Nginx (“engine x”) 是俄罗斯人Igor Sysoev(塞索耶夫)编写的一款高性能的 HTTP 和反向代理服务器。也是一个IMAP/POP3/SMTP代理服务器;也就是说,Nginx本身就可以托管网站,进行HTTP服务处理,也可以作为反向代理服务器使用。
Nginx的应用现状
淘宝、新浪博客、新浪播客、网易新闻、六间房、56.com、Discuz!、水木社区、豆瓣、YUPOO、海内、迅雷在线 等多家网站使用 Nginx 作为Web服务器或反向代理服务器。
Nginx的特点
-
**跨平台:**Nginx 可以在大多数 Unix like OS编译运行,而且也有Windows的移植版本。
-
**配置异常简单:**非常容易上手。配置风格跟程序开发一样,神一般的配置
-
**非阻塞、高并发连接:**数据复制时,磁盘I/O的第一阶段是非阻塞的。官方测试能够支撑5万并发连接,在实际生产环境中跑到2~3万并发连接数.
高并发:其实就是使用技术手段使得系统可以并行处理很多的请求!衡量指标常用的有响应时间,吞吐量,每秒查询率QPS,并发用户数。响应时间:系统对请求做出响应的时间。你简单理解为一个http请求返回所用的时间。 吞吐量:单位时间内处理的请求数量。 QPS:每秒可以处理的请求数 并发用户数:同时承载正常使用系统功能的用户数量。也就是多少个人同时使用这个系统,这个系统还能正常运行。这个用户数量就是并发用户数了
-
**内存消耗小:**处理大并发的请求内存消耗非常小。在3万并发连接下,开启的10个Nginx 进程才消耗150M内存(15M*10=150M)。
-
**成本低廉:**Nginx为开源软件,可以免费使用。而购买F5 BIG-IP、NetScaler等硬件负载均衡交换机则需要十多万至几十万人民币 。
-
**内置的健康检查功能:**如果 Nginx Proxy 后端的某台 Web 服务器宕机了,不会影响前端访问。
**节省带宽:**支持 GZIP 压缩,可以添加浏览器本地缓存的 Header 头。
**稳定性高:**用于反向代理,宕机的概率微乎其微
Nginx启动
-
到官网下载Windows版本,下载地址:nginx.org/en/download…
-
解压到磁盘任一目录(注意:nginx解压后的文件夹不能放在中文目录下。)
-
修改配置文件
-
启动服务:
•直接运行nginx.exe
Nginx服务器默认占用的是80端口号,而在window10中端口号80已经被其它的应用程序占用,所以这里可以修改一下Nginx的端口号,在conf目录下找到nginx.conf文件,该文件就是Nginx服务的配置文件,通过该配置文件可以修改Nginx的端口号,当然后期针对Nginx服务器的配置都是通过该文件完成的。
在这里,我将端口号修改成了:8081,所以在浏览器的地址栏中,输入:http://localhost:8081 可以打开默认的欢迎页面,表示Nginx服务启动成功。
下面我们要做的就是将我们的程序部署到Nginx
中。
现在,我们可以将做好的网站页面拷贝到Nginx
中的html
目录中,然后在地址栏中输入:
http://localhost:8081/
就可以看到对应的页面了,然后单击菜单,发现可以进行留有的切换。当单击刷新按钮后,发现出现了404的错误。
原因,点击刷新按钮就会向服务器发送请求,而在服务端没有对应的文件,所以会出现404的错误。
下面我们需要对Nginx
服务器进行配置,找到conf
目录下的nginx.conf
.
然后进行如下的配置:
location / {
root html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
当在地址栏中输入/
的时候,会请求根目录也就是html
目录中的index.html
.
现在,我们又加了try_files
配置,表示尝试访问文件。
$uri
表示根据所请求的url
地址查找对应文件,如果找到了返回,没有找到。
将$uri
作为目录,查找该目录下的index.html
,如果找到就返回,没有找到,则直接返回html
目录下面的index.html
文件。
而现在我们已经将我们做好的页面拷贝到了html
目录下面,所以直接将我们的页面返回了。
下面可以进行测试。
测试之前需要重新启动服务器。
打开cmd
,然后定位到Nginx
的目录,输入以下命令重新启动服务器。
nginx -s reload
这时的执行流程是:当单击浏览器中的刷新按钮后,会向服务器发送请求,服务接收到请求后,发现没有所访问的文件,但是,由于我们配置了try_files
,所以会将html
目录下面的index.html
页面的内容返回,返回给浏览器后,浏览器会根据路由来进行处理,也就是查找对应组件进行渲染。
转载自:https://juejin.cn/post/7356894848517341203