简介
本文主要介绍在vue工程下vue-router的使用教程。
环境:
# node --verion // v12.x# npm --version // 6.x# vue --version // @vue/cli 4.3.1# npm install vue-router // version 3.x
简单使用
添加home、list、about页
创建router/index.js, 并在main.js中引用, 在app.vue中添加相应标签
router/index.js
import Vue from 'vue'import VueRouter from 'vue-router'import Home from '../views/Home'import List from '../views/List'import Detail from '../views/Detail'import About from '../views/About'Vue.use(VueRouter)export default new VueRouter({// mode: 'history',routes: [{path: '/home',alias: '/index',name: 'home',component: Home},{path: '/list',name: 'list',component: List},{path: '/detail',name: 'detail',component: Detail},{path: '/about',name: 'about',component: About},{path: '*',name: 'NotFoundComponent',component: () => import('../views/NotFoundComponent')}]})
main.js
import router from './router'new Vue({render: h => h(App),router,}).$mount('#app')
app.vue
<router-link to="/home">home</router-link><router-link to="/list">list</router-link><router-link to="/about">about</router-link><router-view></router-view>
跳转
this.$router.push(`/list`)this.$router.push(`/detail/${id}`)// 方式2this.$router.push({ name: 'list' })
导航及传参
router.push(location, onComplete?, onAbort?)
导航(声明式/编程式)
<router-link to="/home">home</router-link>// 等价于<a @click="navHome">home</a>navHome () {this.$router.push('/home')}
path 传参
// /detail/200333this.$router.push(`/detail/${id}`)需要修改router配置path: '/detail/:id',// vue.$routefullPath: "/detail/200333"params: {id: "200333"}path: "/detail/200333"query: {}
params 传参
this.$router.push({name: 'detail', params: {id,}})// warn -> key=name// vue.$routefullPath: "/detail"params: {id: 200333}path: "/detail"
query 传参
this.$router.push({path: 'detail', query: { id, }})// vue.$routefullPath: "/detail?id=200333"path: "/detail"query: {id: 200333}
嵌套?
导航拦截(导航守卫)
钩子函数(组件中的守卫)
beforeRouteEnter (to, from, next) {// console.log(to, from, next)next()},beforeRouteUpdate (to, from, next) {// TODOnext()},beforeRouteLeave (to, from, next) {// ...next()},
应用场景
beforeRouteEnter (to, from, next) {// console.log(to, from, next)const { params } = toconst isCreate = JSON.stringify(params) === '{}'to.meta.title = `${isCreate ? '新建' : '编辑'}地址`next()},
其他配置
重定向
{path: '/',redirect: '/home'},
别名
{path: '/home',alias: '/index',name: 'home',component: Home},
容错显示(匹配, 需要放置在最底部)
{path: '*',name: 'NotFoundComponent',component: () => import('../views/NotFoundComponent')}
模式
mode: hash|history
keep-alive
<keep-alive><router-view></router-view></keep-alive>// meta.keepAlive{path: '/about',name: 'about',component: About,keepAlive: true},
源码解析
原生导航对象
原理分析
