前端路由 vue-router
1.路由就是通过互联的网络吧信息从源地址传输到目的的地址活动
2.路由机制
路由包括路由和转发.
路由器 -> 公网IP -> 映射表 -> 内网IP
映射表: [内网ip1:电脑标识1,内网ip2:电脑标识2]
3.前端路由
URL和前端页面的映射关系
----->vue router
核心: 改变URL,但是页面不进行整体的刷新
改变URL,但是页面不进行整体的刷新
1.URL的hash
URL的hash也就是锚点,本质上是改变window.location的herf属性
我们可以通过直接赋值location.hash来改变href,但是页面不发生刷新
2.HTML5的history
history.pushState({},'','home')
history.pushState相当于栈的操作,先进后出,弹栈和入栈的操作。
history.pushState入栈;
history.back()出栈;
history.go(-1) 相当于 history.back();
history.forward 相当于history.go(1);
history.replaceState():不能返回;
路由跳转
- 11.使用
<router-link>
组件:<router-link>
是Vue Router提供的组件,用于生成路由链接。可以在模板中使用它来创建跳转链接。例如:
<router-link to="/about">about<router-link>
- 2.使用$router.push方法: $router是Vue Router实例的引用,可以通过它调用路由跳转的方法。例如:
/在组件方法中使用
this.$router.push( ' / about ' );
//在Vue Router实例外部使用
import { createRouter, createwebHistory } from 'vue-router' ;
const router = createRouter({
history: createwebHistory(),
routes: [...]
}) ;
router.push( ' / about ' );
- 3.使用命名路由:如果你在定义路由时给路由规则指定了名称,可以使用名称来进行跳转。例如
/在组件方法中使用
this.$router.push({ name: 'about'});
//在Vue Router实例外部使用
router.push({ name: 'about' });
安装和使用vue-router
1.安装vue-router
npm install vue-router --save
2.在模块化工程中使用它
需要用Vue.use()来安装其功能
- 导入路由对象,并且调用Vue.use(VueRouter)
- 创建路由实例,并传入路由映射配置
- 在Vue实例中挂载创建的路由实例
3.使用vue-router的步骤
- 创建路由组件
- 配置路由映射,组件和路径映射关系
- 使用路由:通过
<router-link><router-view>
4.router-link与router-view
<router-link>
:该标签是一个vue-router中已经内置的组件,它会被渲染成一个<a>
标签
<router-view>
:该标签会根据当前的路径,动态渲染出不同的组件
网页的其他内容,比如顶部的标题/导航,或者底部的一些版权信息等会和处于同一个等级。
在路由切换时,切换的是挂载的组件,其他内容不会发生改变。
5.vue-router 代码实例
(1)App.vue
<template>
<div id="app">
<router-link to="/home" >首页</router-link>
<router-link to="/about">关于</router-link>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
(2)Home.vue
<template>
<div>
<h2>我是首页</h2>
<p>我是首页内容, 哈哈哈</p>
</div>
</template>
<script>
export default {
name: "Home"
}
</script>
<style scoped>
</style>
(3)About.vue
<template>
<div>
<h2>我是关于</h2>
<p>我是关于内容, 呵呵呵</p>
</div>
</template>
<script>
export default {
name: "About"
}
</script>
<style scoped>
</style>
(4)main.js
import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false
new Vue({
el: '#app',
router,
render: h => h(App)
})
(5)index.js
// 配置路由相关的信息
import VueRouter from 'vue-router'
import Vue from 'vue'
import Home from '../components/Home'
import About from '../components/About'
// 1.通过Vue.use(插件), 安装插件
Vue.use(VueRouter)
// 2.创建VueRouter对象
const routes = [
{
path: '',
// redirect重定向
redirect: '/home'
},
{
path: '/home',
component: Home
},
{
path: '/about',
component: About
}
]
const router = new VueRouter({
// 配置路由和组件之间的应用关系
routes,
mode: 'history',
linkActiveClass: 'active'
})
// 3.将router对象传入到Vue实例
export default router
(6)浏览器展示
router-line的其他属性
tag:tag可以指定router-link之后渲染成什么组件,比如,此时就是一个button了;
replace:增加replace属性,就相当于replaceState;
class:可以为标签增加样式,比如选中的会自动赋值router-link-active;
active-class=“active”
:选中的;也可以在router组件中配置linkActiveClass: 'active';
通过代码跳转路由:
<script>
export default {
name: 'App',
methods: {
homeClick() {
// 通过代码的方式修改路由 vue-router
// push => pushState
this.$router.push('/home')
//this.$router.replace('/home')
console.log('homeClick');
},
aboutClick() {
this.$router.push('/about')
//this.$router.replace('/about')
console.log('aboutClick');
}
}
}
</script>
vue-router动态路由的使用
在某些情况下,一个页面的path路径可能是不确定的,比如我们进入用户界面时,希望路径中存在用户id,这种path和Component相互匹配的关系,我们称之为动态路由,也是路由传递数据的一种方式。
this.$route表示正在活跃的路由。
获取路径中的姓名:
...
<router-link :to="'/user/'+userId">用户</router-link>
...
<template>
<div>
<h2>我是用户界面</h2>
<p>我是用户的相关信息, 嘿嘿嘿</p>
<h2>{{userId}}</h2>
<h2>{{$route.params.id}}</h2>
<button @click="btnClick">按钮</button>
</div>
</template>
<script>
export default {
name: "User",
computed: {
userId() {
return this.$route.params.id
}
}
</script>
vue-router打包文件的解析
路由懒加载
1.什么是懒加载
当打包构建应用时,JavaScript包会变得非常大,影响页面加载。
如果我们能吧不同路由对应的组件分割成不同的代码块,然后当路由被访问的时候才加载对应组件,这样就更加高效了
2.懒加载的方式
(1)结合Vue的异步组件和Webpack的代码分析
const Home = resolve => { require.ensure(['../components/Home.vue'],
() => { resolve(require('../components/Home.vue')) })};
(2)amd写法
const About = resolve => require(['../components/About.vue'], resolve);
(3)在ES6中,我们可以有更加简单的写法来组织Vue异步组件和Webpack的代码分割
const Home = () => import('../components/Home.vue')
3.代码实例
index.js
// import Home from '../components/Home'
// import About from '../components/About'
// import User from '../components/User'
// 懒加载方式
const Home = () => import('../components/Home')
const About = () => import('../components/About')
const User = () => import('../components/User')
路由嵌套
1.嵌套路由是一个很常见的功能
比如在home页面中,我们希望通过/home/news和/home/message访问一些内容;
一个路径映射一个组件,访问这两个路径也分别渲染这两个组件;
2.实现嵌套路由的两个步骤
1.创建对应的子组件,并且在路由映射中配置对应的子路由;
2.在组件内部使用<router-view>
标签;
3.嵌套路由代码实例
(1)index.js
// 配置路由相关的信息
import VueRouter from 'vue-router'
import Vue from 'vue'
const Home = () => import('../components/Home')
const HomeNews = () => import('../components/HomeNews')
const HomeMessage = () => import('../components/HomeMessage')
const About = () => import('../components/About')
const User = () => import('../components/User')
const Profile = () => import('../components/Profile')
// 1.通过Vue.use(插件), 安装插件
Vue.use(VueRouter)
// 2.创建VueRouter对象
const routes = [
{
path: '',
// redirect重定向
redirect: '/home'
},
{
path: '/home',
component: Home,
meta: {
title: '首页'
},
children: [
{
path: 'news',
component: HomeNews
},
{
path: 'message',
component: HomeMessage
}
]
}
]
const router = new VueRouter({
// 配置路由和组件之间的应用关系
routes,
mode: 'history',
linkActiveClass: 'active'
})
// 3.将router对象传入到Vue实例
export default router
(2)Home.vue
<template>
<div>
<h2>我是首页</h2>
<p>我是首页内容, 哈哈哈</p>
<router-link to="/home/news">新闻</router-link>
<router-link to="/home/message">消息</router-link>
<router-view></router-view>
<h2>{{message}}</h2>
</div>
</template>
<script>
export default {
name: "Home",
data() {
return {
message: '你好啊',
path: '/home/news'
}
}
}
</script>
<style scoped>
</style>
(3)HomeNews.vue
<template>
<div>
<ul>
<li>帅哥1</li>
<li>帅哥2</li>
<li>帅哥3</li>
<li>帅哥4</li>
</ul>
</div>
</template>
<script>
export default {
name: "HomeNews"
}
</script>
<style scoped>
</style>
vue-router参数传递
1.传递参数主要有两种类型: params和query
params的类型:
1.配置路由格式: /router/:id
2.传递的方式: 在path后面跟上对应的值
3.传递后形成的路径: /router/123, /router/abc
query的类型:
1.配置路由格式: /router, 也就是普通配置
2.传递的方式: 对象中使用query的key作为传递方式
3.传递后形成的路径: /router?id=123, /router?id=abc
2.代码实例
(1)传值
<script>
...
export default {
...
methods: {
userClick() {
this.$router.push('/user/' + this.userId)
},
profileClick() {
this.$router.push({
path: '/profile',
query: {
name: 'kobe',
age: 19,
height: 1.87
}
})
}
}
}
</script>
(2)取值
<template>
<div>
<h2>{{$route.query.name}}</h2>
<h2>{{$route.query.age}}</h2>
<h2>{{$route.query.height}}</h2>
</div>
</template>
vue-router全局导航守卫
1、生命周期函数
<script>
export default {
name: "Home",
data() {
return {
message: '你好啊',
path: '/home/news'
}
},
created() {
console.log('home created');
},
destroyed() {
console.log('home destroyed');
},
// 这两个函数, 只有该组件被保持了状态使用了keep-alive时, 才是有效的
activated() {
this.$router.push(this.path);
console.log('activated');
},
deactivated() {
console.log('deactivated');
},
beforeRouteLeave (to, from, next) {
console.log(this.$route.path);
this.path = this.$route.path;
next()
}
}
</script>
2、前置守卫
(1)动态修改标题
跳转前回调
// 前置守卫(guard)
router.beforeEach((to, from, next) => {
// 从from跳转到to
document.title = to.matched[0].meta.title
// 必须调用next(),表示执行下一步的意思
next()
})
(2)beforeEach源码分析
(3)跳转后回调
// 后置钩子(hook)
router.afterEach((to, from) => {
// console.log('--我是CSDN哪吒--');
})
keep-alive与vue-router
keep-alive是vue内置的一个组件,可以使被包含的组件保留状态,或避免重新渲染。
router-view也是一个组件,如果直接被包在keep-alive里面,所有路径匹配到的试图组件都会被缓存。