Vue - 路由

前端路由

vue-router

vue-router官方文档

vue-router安装

npm i vue-router@3.5.2 -S

创建路由模块

再src源代码目录下,新建router/index.js路由模块,并初始化如下代码:

// 1、导入Vue和VueRouter
import Vue from 'vue'
import VueRouter from 'vue-router'
// 2、安装VueRouter插件
Vue.use(VueRouter)
// 3、创建路由的实例对象
const router = new VueRouter({

})
// 4、向外共享router
export default router

挂载路由模块

再main.js中将vue-router挂在到vue中

import router from '@/router/index.js'

new Vue(){
	render:h=>h(App);
	router
}

路由的基本使用

//App.vue
<router-link to="/home"></router-link>
//占位符
<router-view></router-view>
//index.js
import Home from '@/components/Home.vue'
const router = new VueRouter({
//routes是一个数组,用来描述地址与组件之间的关系---路由规则
	routes:[
	{path:'/' , redirect:'/home'},
	{path:'/home' , component:Home}
	]
})

嵌套路由

//index.js
const router = new VueRouter({
//routes是一个数组,用来描述地址与组件之间的关系---路由规则
	routes:[
	{path:'/' , redirect:'/home'},
	{
		path:'/home' , 
		component:Home,
		redirect:'/home/tab' //重定向
		children:[ //子路由规则
			{path:'',component:Tab} //默认子路由
			{path:'tab',component:Tab}
		]
	}]
})

路由传递参数

query传递参数

to 的字符串写法
<templete>
<router-link 
	:to="`/home/message/detail?id=${m.id}&title=${m.title}`">
	{{m.title}}
</router-link>

</templete>
to 的对象写法
<templete>
 <router-link
    :to="{
      name: 'detail',
      query: {
        id: m.id,
        title: m.title,
      },
    }">
    {{ m.title }}
</router-link>
</templete>

或者使用path

<templete>
 <router-link
    :to="{
     path: '/home/message/detail',
     query: {
        id: m.id,
        title: m.title,
      },
    }">
    {{ m.title }}
</router-link>
</templete>

params传递参数

to 的字符串写法
<router-link 
	:to="`/home/message/detail/${m.id}/${m.title}`">
	{{m.title}}
</router-link>
to 的对象写法

⚠️ 此写法必须使用name不能使用path属性 !

<router-link
   :to="{
     name: 'detail',
     params: {
       id: m.id,
       title: m.title,
     },
   }">
   {{ m.title }}
</router-link>

编程式导航

push

this.$router.push({
  name: "detail",
  query: {
    id: m.id,
    title: m.title,
  },
});

replace

this.$router.replace({
  name: "detail",
  query: {
    id: m.id,
    title: m.title,
  },
});

go

//-1表示往后推一层
this.$router.go(-1);

导航守卫

可以控制路由的访问权限

全局前置守卫

const router = new VueRouter({...})
//调用路由实例对象的beforeEach方法
//每次发生路由导航跳转的时候,都会自动触发cb这个回调函数
router.beforeEach((to,from,next)=>{
	//to是将要访问的路由的信息对象
	//from是将要离开的路由的信息对象
	//next是一个函数,调用next()表示放行,允许这次路由导航
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值