1.路由使用
//安装
npm install vue-router --save-dev
//main.js中引入
import VueRouter from './router'
Vue.use(VueRouter)
//配置路由
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{path: '/',name: 'home',component: Home},
{path: '/helloworld',name: 'home',component: HelloWorld}
]
})
//在Vue实例中使用
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
//App.vue里添加
<router-view/>
//页面跳转标签
<router-link to="/">Home</router-link>
可将路由js文件模块化使用,根目录下新建router文件夹,新增index.js
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export default new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/',
name: 'father',
component: () => import('@/views/CFather.vue')
}
]
})
main.js里
import router from '@/router'
2.用于学习的Demo搭建
vue-cli3项目根目录components文件夹下新建Header.vue
<template>
<div class="header">
<router-link to="/" class="nav-link" exact>主页</router-link>
<router-link to="/about" class="nav-link">关于我们</router-link>
</div>
</template>
<script>
export default {
name:'app-header'
}
</script>
<style>
.header {
text-align: center;
}
.nav-link {
text-decoration: none;
}
</style>
vue-cli3项目根目录view文件夹下新建三个组件Home.vue、About.vue、404.vue(这里仅展示一个,其他两个代码类似)
<template>
<div>
<app-header></app-header>
<h1>Home</h1>
</div>
</template>
<script>
import Header from '@/components/Header'
export default {
components: {
"app-header": Header
}
}
</script>
<style>
.container {
text-align: center;
}
</style>
router文件夹下index.js配置路由
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export default new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/',
name: 'home',
component: () => import('@/views/Home.vue')
},
{
path: '/about',
name: 'about',
component: () => import('@/views/About.vue')
},
{
path: '/404',
name: '404',
component: () => import('@/views/404.vue')
},
{
path:'*',
redirect:'/404'
}
]
})
3.路由相关属性
(1)tag
<!-- <router-link>真实DOM是<a>标签,使用tag修改 -->
<router-link to="/" tag="div">Home</router-link>
(2)exact控制样式消失
<router-link :to="{name:homeLink}" exact>Home</router-link>
<router-link :to="{name:homeLink}" exact>Home2</router-link>
(3)redirect路由重定向
const routes = {
{path:'/',component:Home},
{path:'*',redirect:'/'}
}
(4)name
const routes = {
{path:'/',name:'homeLink',component:Home},
{path:'*',redirect:'/'}
}
<!-- 使用 -->
<router-link :to="{name:'homeLink'}" >Home</router-link>
4.路由跳转和传参
(1)路由跳转
methods:{
doToMenu(){
//跳转到上一个浏览的页面
this.$router.go(-1)
//指定跳转的地址
this.$router.replace('/menu')
//指定跳转路由的名字下
this.$router.replace({name:'homeLink'})
//通过push进行跳转
this.$router.push('/menu')
this.$router.push({name:'homeLink'})
}
}
(2)路由传参
<button @click="onNavToTargetView">点击跳转到目标路由页面</button>
方法一:
配置路由:
{
path: '/user',
name: 'user',
component: ()=> import(./view/User.vue)
}
methods:
onNavToTargetView() {
//注意name不能换成path:"/user"
this.$router.push({name:"user", params:{userName:"lyc"}})
}
User.vue组件:
//User.vue组件中就可以通过$route的params获取到
this.$route.params.userName;
方法二:
配置路由:
{
path: '/user',
name: 'user',
component: ()=> import(./view/User.vue)
}
methods:
onNavToTargetView() {
this.$router.push({path:"/user",query:{userName:"lyc"}})
}
User.vue组件:
//User.vue组件中就可以通过$route的query获取到,注意是query不是params
this.$route.query.userName;
注意:此时请求的url是:http://localhost:8082/user?userName=lyc
方法三:
配置路由:
{
path: '/user/:userName',
name: 'user',
component: ()=> import(./view/User.vue)
}
methods:
onNavToTargetView() {
this.$router.push({path:`/user/${userName}`})
}
User.vue组件:
//User.vue组件中就可以通过$route的params获取到
this.$route.params.userName;
5.二级路由和三级路由
使用children属性进行嵌套
const routes = {
{path:'/about',name:'aboutLink',redirect:'/about/contact',component:About,children:[
{path:'/about/contact',name:'contactLink',component:Contact},
{path:'/history',name:'historyLink',component:History},
{path:'/delivery',name:'deliveryLink',component:Delivery},
]}
}
注意:
1.第一行 redirect:'/about/contact' 表示默认展示哪个页面
2.在 About组件的模板需要添加一个 <router-view/>才能够嵌套
6.导航守卫
(1)全局守卫
router.beforeEach((to,from,next) => {
let hasToken = true
if(hasToken){
if (to.path === '/login') {
next({ path: '/' })
}else{
next()
}
}
})
(2)后置钩子
router.afterEach((to,from) => {
alert("after each")
})
(3)路由独享守卫
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{path: '/',name: 'home',component: Home},
{path: '/helloworld',name: 'home',component: HelloWorld,beforeEnter:(to,from,next) => {
alert("非登录状态,不能访问页面!")
}}
]
})
(4)组件内守卫
<script>
export default {
data() {
return {
name:'Henry'
}
},
beforeRouteEnter (to, from, next) {
// 在渲染该组件的对应路由被 confirm 前调用
// 不!能!获取组件实例 `this`
// 因为当守卫执行前,组件实例还没被创建
//提示Hello undefined,因为守卫在数据渲染前执行,解决方法在next里写回调
// alert("Hello "+ this.name)
next(vm => {
alert("Hello "+ vm.name)
})
},
beforeRouteUpdate (to, from, next) {
// 在当前路由改变,但是该组件被复用时调用
// 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
// 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
// 可以访问组件实例 `this`
},
beforeRouteLeave (to, from, next) {
// 导航离开该组件的对应路由时调用
// 可以访问组件实例 `this`
if(confirm("确定离开吗") == true){
next()
}else{
next(false)
}
}
}
</script>
7.路由元信息
内容比较好理解,可参考官网:https://router.vuejs.org/zh/guide/advanced/meta.html
8.路由的滚动行为
//配置路由
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{path: '/',name: 'home',component: Home},
{path: '/helloworld',name: 'home',component: HelloWorld}
],
scrollBehavior (to,from,savedPosition) {
//savedPosition 仅当通过浏览器前进后退时候才触发
//定位到指定位置
return {x:0,y:100}
//定位到控件位置
// return {selector: '.btn'}
//滑动时候记住当前位置
// if (savedPosition) {
// return savedPosition
// }else{
// return {x:0,y:0}
// }
}
})
9.路由懒加载
const router = new VueRouter({
routes: [
{ path: '/foo', component: ()=> import(./view/User.vue)}
]
})
10.路由代码抽离,复用<router-view>
应用场景:比如我们想在 主页 中展示 历史订单 快递信息 点餐文档 这三个部分的信息,可以使用 router-view 复用。
<!-- App.vue里复用别的页面的Component -->
<div>
<router-view name="orderingGuide"></router-view>
<router-view name="delivery"></router-view>
<router-view name="history"></router-view>
</div>
import Home from '@/views/Home'
import orderingGuidefrom '@/views/orderingGuide'
import delivery from '@/views/delivery'
import historyfrom '@/views/history'
//路由表
const routes = {
{path:'/',name:'homeLink',components:{
'Home': Home,
'orderingGuide':OrderingGuide,
'delivery':Delivery,
'history': History
}},
{path:'*',redirect:'/'}
}
11.路由监控
watch: {
'$route' (to, from) {
// 对路由变化作出响应...
console.log(to)
console.log(from)
}
}
网友评论