Vue Router 配置详解及功能介绍

Vue 3.x And Vue Router Learning

node 环境支持

npm install -g @vue/cli 安装脚手架3.x

npm install -g @vue/cli-init 安装脚手架2.x

替换淘宝镜像

npm install -g cnpm --registry=http://registry.npm.taobao.org

cnpm install [name]

vue-cli初始化项目

1.Vue Cli2

vue init webpack my-project

2.Vue Cli3

vue create my-project

pic01.jpg

runtime-compiler 与 runtime-only的区别?

1.runtime-compiler:先在components里面注册组件,然后在template中使用组件

template ---> ast (abstract syntax tree)--> render --->visual dom ---> reality dom (UI界面)

2.runtime-only:直接通过render()函数,使用组件/传递template模板内容

render --> visual dom --> reality dom (UI界面)

注释:runtime-only下不允许出现template;但组件中的template会被编译成对象,不影响 render函数运行

pic02.jpg

关于子组件中的template模板是否影响runtime-only版本运行?

子组件在被入口文件调用的时候会被编译成对象,所以不存在template的影响

通过 console.log(App) 查看传给根组件的内容是否为对象类型

pic03.jpg

npm run build / npm run dev运行原理图

pic04.jpg
pic05.jpg

注:made by coderwhy from bilibili

vue-cli3手动配置的文件保存在 C:/User/Administrator/.vuerc

扩展:.xxxrc rc ----> run command


前端路由相关知识点

1.url更新不刷新页面方法(包含h5语法)

location.hash = ''

history.pushState({},'','') // 会保存历史记录

history.back() // 后退

history.forward()// 前进

history.replaceState({},'','') // 不会保存历史记录

history.go( -x / 0 / x ) // 后退x步、刷新、前进x步

2.安装路由 vue-router

npm install --save vue-router

3.vue-router基本配置

router/index.js配置

// 配置路由相关的信息
import VueRouter from 'vue-router'
import Vue from 'vue'

// 导入组件
import Xxx from '../components/Xxx'
......

// 1.通过 Vue.use( plugin ),安装插件
Vue.use(VueRouter)

// 配置路由和组件的映射关系,一个路由对应一个对象
const routes = [
{ path:'/xxx', component:Xxx }
]

// 2.创建VueRouter对象
const router = new VueRouter({
// 配置路由和组件之间的关系
routes
})

// 3.将router对象传入到Vue实例
export default router

main.js配置

import Vue from 'vue'
import App from './App'
// 导入路由
import router from './router'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
el: '#app',
// 挂载路由
router, render: h => h(App) })​

4.使用路由 <router-link to=""><router-view>

App.vue配置

<template> <div id="app"> <router-link to="/xxx">Router</router-link> <router-view></router-view> // 用于显示 </div> </template>

<script> export default { name: 'App' }
</script>

<style>

</style>

注释:
1.<router-view>在代码中的位置决定其内容在网页中的布局
2.默认路由重定向

一般用于显示默认的首页
{
path:'',
redirect:'/xxx',
component:Xxx
},

5.关于默认的hash模式的更改

index.js配置
const router = new VueRouter({
// 配置路由和组件之间的关系
routes,
mode:'history' // 改为 H5 模式 (地址栏 URL 的显示模式)
})

6.router-link 的其他属性补充

a. tag 属性

默认情况下,router-link会被渲染成 a标签;tag属性可选择其渲染成的标签

eg. <router-link tag="button/li/..."></router-link>

b. replace 属性

replace 不会留下history记录,即浏览器后退键返回不能返回上一个页面

eg. <router-link to="/about" tag="button" replace>关于</router-link>

c. linkActiveClass 属性

路由跳转时动态添加样式

const router = new VueRouter({
// 配置路由和组件之间的关系
routes,
mode:'history',
linkActiveClass:'active' // css中应该添加 active 样式
})

d. 通过代码的方式修改路由 vue-router
  1. 监听按钮点击事件
  1. 调用 this.$router.push('路径') / this.$router.replace('路径')
注释:push 和 replace 的区别在于是否会留下 history 记录

7. 动态路由的使用

index.js 文件配置

const routes = [
{ path: '/xxx/:aaa', component:Xxx }
]

App.vue 文件配置

<router-link :to="'/xxx/'+aaa" tag="button" replace>...</router-link>

data(){
return { userId:'aaa' }
},

component/xxx.vue 组件配置

this.$route.params.xxx ==> xxx 为要获取的变量名
{{ $route.params.userId }}可以动态获取url中的动态路由中的参数

computed: { userId() { return this.$route.params.userId }}

8. 路由懒加载 lazy

方式一:结合Vue的异步组件和Webpack的代码分析

const Xxx = resolve => {require.ensure(['../components/Xxx.vue'],() =>

{resolve(require('../components/Xxx.vue')) })};

方式二:AMD写法

const Xxx = resolve => require(['../components/Xxx.vue'],resolve);

方式三:在ES6语法

const Xxx = () => import('../components/Xxx.vue')

pic08.jpg
采用lazy加载方式后打包文件前后对比
pic06.jpg
pic07.jpg

9. 嵌套路由

配置方法:

1 > 在所嵌套的页面组件中添加<router-link><router-view>

2 > index.js文件中,在路由映射表中配置嵌套路由映射关系到所嵌套路由 children属性

{
path: '/home', component: () => import('../components/Home'),
children: [
{ path:'', redirect:'/home/news', component:null },
{ path:'news', component:()=> import('../components/HomeNews') },
{ path:'message', component:()=> import('../components/HomeMessage') }
]
},

注释:务必注意文件中的路径使用,' / ' 不能丢

完整的URL组成 ---> scheme : // host : port / path ? query # fragment (片段 )
关于router-link传递query参数

一、router-link中传递

<router-link :to="{ path:'/profile', query:{ name:'lemon', age:'22' } }" tag="button" replace>profile</router-link>

二、methods中传递

this.$router.push({ path:'/profile', query:{ name:'lemon', age:'22' } })
this.$router.replace({ path:'/profile', query:{ name:'lemon', age:'22' } })

三、获取query字符串对象

this.$route.query.property
this.$route 获取活动状态的路由
this.$route.query 获取活动路由中的查询字符串对象
property 为查询字符串对象中的属性

注意:所有的组件都继承Vue的原型

10. 导航守卫

理解vue生命周期及生命周期函数

pic09.jpg

created() 创建组件时回调

mounted()组件被挂载时回调

updated() 数据更新时回调

destroyed()组件销毁时回调
......
注释:document.title 获取导航title值
同步导航title两种方法

1. 静态同步:使用生命周期函数(弊端在于每个导航组件都必须添加一次created函数)

created() { document.title = "用户" }

2. 动态添加:使用router中的beforEach函数(在index.js中配置)

前置守卫:在路由跳转前进行回调
router.beforeEach((to, from, next) => {
document.title =to.matched[0].meta.title // to:获取到的时this.$route 活动路由
next() // 指定next否则 App 将无法自动进行下一步
})

注意:必须在每一个路由对象中配置meta元数据
const routes = [
{path: '/user/:userId', meta: {title: '用户'}, component: () => import('../components/User')},
]

注意:必须在每一个路由对象中配置meta元数据
const routes = [
{path: '/user/:userId', meta: {title: '用户'}, component: () => import('../components/User')},
]

关于to.matched[0].meta图解,下方打印出的是活动路由对象

pic10.jpg
补充:1. 后置钩子(在路由跳转结束后回调),也就是afterEach(),不需要手动调用next()函数
2. 路由独享的守卫
3. 组件内的守卫

Vue Router 导航守卫补充知识

11. keep-alive

1. keep-alive 是 Vue 内置的一个组件,可以使被包含的组件保留状态,或避免重新渲染
2. router-view 也是一个组件,如果直接被包在 keep-alive 中,所有路径匹配到的视图组件都会被缓存
记录上一次路由离开时的状态 ---->beforeRouteLeave(to,from,next) { }
<router-view><keep-alive> 包裹时有效
deactivated(){}
activated(){}

Writen by LemonCoder: 2297547342@qq.com

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容