Vue中vue-router(路由)的使用

Vue中vue-router(路由)的使用

基本使用

  • 一个路由(route)就是一组映射关系(key-value),多个路由需要路由器(router)进行管理
  • 前端路由:key是路径,value是组件
  • 安装vue-router:npm i vue-router
  • 应用插件:Vue.use(VueRouter)
修改main.js文件
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//引入VueRouter
import VueRouter from 'vue-router'
//引入路由器
import router from './router'

//应用插件
Vue.use(VueRouter)

//创建vm
new Vue({
	el:'#app',
	render: h => h(App),
	router:router
})
创建router/index.js文件
// 该文件专门用于创建整个应用的路由器
import VueRouter from 'vue-router'
//引入组件
import About from '../components/About'
import Home from '../components/Home'

//创建并暴露一个路由器
export default new VueRouter({
	routes:[
		{
			path:'/about',
			component:About
		},
		{
			path:'/home',
			component:Home
		}
	]
})
编写App.vue文件
<template>
  <div id="app">
    <div>
      <!-- Vue中借助router-link标签实现路由的切换 -->
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link>
    </div>
    <!-- 指定组件的呈现位置 -->
    <router-view/>
  </div>
</template>
创建About.vue
<template>
  <div>
    <h1>This is an about page</h1>
  </div>
</template>
创建Home.vue
<template>
  <h2>
    this is home page
  </h2>
</template>
  • 路由组件通常存放在page文件夹,一般组件通常存放在components文件夹
  • 通过切换,隐藏了的路由组件,默认是被销毁掉的,需要的时候再去挂载
  • 每个组件都有自己的$route属性,里面存储着自己的路由信息
  • 整个应用只有一个router,可以通过组件的$router属性获取到。

多级路由

使用children配置项。

//创建并暴露一个路由器
export default new VueRouter({
	routes:[
		{
			path:'/about',
			component:About
		},
		{
			path:'/home',
			component:Home,
			children:[
				{
					path:'news',
					component:News,
				},
				{
					path:'message',
					component:Message,
				}
			]
		}
	]
})

路由跳转要写完整路径

<router-link to="/home/news">News</router-link>

路由的query参数

参数传递

<!-- 跳转并携带query参数,to的字符串写法 -->
   <router-link :to="/home/message/detail?id=666&title=你好">跳转</router-link>
   				
   <!-- 跳转并携带query参数,to的对象写法 -->
   <router-link 
   	:to="{
   		path:'/home/message/detail',
   		query:{
   		   id:666,
         title:'你好'
   		}
   	}"
   >跳转</router-link>

参数接收

$route.query.id
$route.query.title

路由命名

  • 作用:可以简化路由的跳转

给路由命名

{
  path:'/demo',
    component:Demo,
      children:[
        {
          path:'test',
          component:Test,
          children:[
            {
              name:'hello' //给路由命名
              path:'welcome',
              component:Hello,
            }
          ]
        }
      	

简化跳转

<!--简化前,需要写完整的路径 -->
<router-link to="/demo/test/welcome">跳转</router-link>

<!--简化后,直接通过名字跳转 -->
<router-link :to="{name:'hello'}">跳转</router-link>

<!--简化写法配合传递参数 -->
<router-link 
             :to="{
                  name:'hello',
                  query:{
                      id:666,
                      title:'你好'
                    }
                  }"
             >跳转</router-link>

路由的param参数

配置路由,声明接收params参数

{
   	path:'/home',
   	component:Home,
   	children:[
   		{
   			path:'news',
   			component:News
   		},
   		{
   			component:Message,
   			children:[
   				{
   					name:'machoul',
   					path:'detail/:id/:title', //使用占位符声明接收params参数
   					component:Detail
   				}
   			]
   		}
   	]
   }

传递参数

 <!-- 跳转并携带params参数,to的字符串写法 -->
   <router-link :to="/home/message/detail/666/你好">跳转</router-link>
   				
   <!-- 跳转并携带params参数,to的对象写法 -->
   <router-link 
   	:to="{
   		name:'machoul',
   		params:{
   		   id:666,
         title:'你好'
   		}
   	}"
   >跳转</router-link>
  • 特别注意:路由携带params参数时,若使用to的对象写法,则不能使用path配置项,必须使用name配置!

参数接收

$route.params.id
$route.params.title

路由的props配置

作用:让路由组件更方便的收到参数,配置在路由定义中

  • 如果props值为对象,该对象中所有的key-value的组合最终都会通过props传给Detail组件
{
	name:'machoul',
	path:'detail/:id',
	component:Detail,
	props:{a:900}
}
  • props值为布尔值,布尔值为true,则把路由收到的所有params参数通过props传给Detail组件
{
	name:'machoul',
	path:'detail/:id',
	component:Detail,
	props:true
}
  • props值为函数,该函数返回的对象中每一组key-value都会通过props传给Detail组件
{
	name:'machoul',
	path:'detail/:id',
	component:Detail,
	props(route){
		return {
			id:route.query.id,
			title:route.query.title
		}
	}
}

router-link的replace属性

  • 作用:控制路由跳转时操作浏览器历史记录的模式

  • 浏览器的历史记录有两种写入方式:分别为pushreplacepush是追加历史记录,replace是替换当前记录。路由跳转时候默认为push

  • 如何开启replace模式:<router-link replace .......>News</router-link>

编程式路由导航

  • 作用:不借助<router-link>实现路由跳转,让路由跳转更加灵活

  • push方法

this.$router.push({
  name:'machoul',
  params:{
    id:xxx,
    title:xxx
  }
})
  • replace方法
this.$router.replace({
  name:'machoul',
  params:{
    id:xxx,
    title:xxx
  }
})
  • 其他
this.$router.forward() //前进
this.$router.back() //后退
this.$router.go() //可前进也可后退

缓存路由组件

作用:让不展示的路由组件保持挂载,不被销毁.

<keep-alive include="News"> 
	<router-view></router-view>
</keep-alive>

路由守卫

全局路由守卫

对路由进行全局权限控制

//全局前置守卫:初始化时执行、每次路由切换前执行
router.beforeEach((to,from,next)=>{
  console.log('beforeEach',to,from)
  if(to.meta.isAuth){ //判断当前路由是否需要进行权限控制
    if(true){ //权限控制的具体规则
      next() //放行
    }else{
      alert('暂无权限查看')
    }
  }else{
    next() //放行
  }
})

//全局后置守卫:初始化时执行、每次路由切换后执行
router.afterEach((to,from)=>{
  console.log('afterEach',to,from)
  if(to.meta.title){
    document.title = to.meta.title //修改网页的title
  }else{
    document.title = 'vue_test'
  }
})
独享路由守卫

对某一个路由进行单独的设置

const router =  new VueRouter({
  routes:[
    {
      name:'zhuye',
      path:'/home',
      component:Home,
      meta:{title:'主页'},
      children:[
        {
          name:'xinwen',
          path:'news',
          component:News,
          meta:{isAuth:true,title:'新闻'},
          beforeEnter: (to, from, next) => {
            console.log('独享路由守卫',to,from)
            if(to.meta.isAuth){ //判断是否需要鉴权
              if(true){
                next()
              }else{
                alert('无权限查看!')
              }
            }else{
              next()
            }
          }
        }
      ]
    }
  ]
})
组件内路由守卫

在组件内对路由进行配置

<template>
  <h2>
    this is home page
  </h2>
</template>

<script>
export default {
  name: 'Home',
  //通过路由规则,进入该组件时被调用
  beforeRouteEnter (to, from, next) {
    console.log('home--beforeRouteEnter',to,from)
    if(to.meta.isAuth){ //判断是否需要鉴权
      if(true){
        next()
      }else{
        alert('无权限查看!')
      }
    }else{
      next()
    }
  },

  //通过路由规则,离开该组件时被调用
  beforeRouteLeave (to, from, next) {
    console.log('home--beforeRouteLeave',to,from)
    next()
  }
}
</script>

路由的两个钩子函数

  • 作用:路由组件所独有的两个钩子,用于捕获路由组件的激活状态。
  • 具体名字:
    • activated路由组件被激活时触发。
    • deactivated路由组件失活时触发。
export default {
  name: 'Home',
  activated() {
    console.log('home is activated')
  },
  deactivated() {
    console.log('home is deactivated')
  }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 3使用Vue Router进行路由拆分可以帮助你更好地组织和管理你的路由配置。以下是一些步骤来实现路由拆分: 1. 安装Vue Router:首先,确保你的项目已经安装了Vue Router。可以通过以下命令进行安装: ``` npm install vue-router@next ``` 2. 创建路由模块:创建一个新的模块来定义和配置你的路由。可以创建一个名为`router.js`的文件,并在其导入VueVue Router: ```javascript import { createRouter, createWebHistory } from 'vue-router'; const routes = [ // 定义你的路由配置 ]; const router = createRouter({ history: createWebHistory(), routes, }); export default router; ``` 3. 定义路由配置:在路由模块,通过`routes`数组来定义你的路由配置。每个路由对象应该包含一个`path`属性和一个`component`属性,分别指定路由的路径和对应的组件。 ```javascript import Home from './components/Home.vue'; import About from './components/About.vue'; const routes = [ { path: '/', component: Home, }, { path: '/about', component: About, }, // 更多路由配置... ]; ``` 4. 在主应用程序使用路由:在你的主应用程序,导入并使用创建的路由实例。你可以在`main.js`文件完成这个步骤: ```javascript import { createApp } from 'vue'; import App from './App.vue'; import router from './router'; const app = createApp(App); app.use(router); app.mount('#app'); ``` 现在,你已经成功拆分了你的路由配置。你可以在每个组件使用`<router-link>`和`<router-view>`来进行导航和渲染路由组件。 注意:以上只是一个简单的示例,你可以根据你的项目需求进行更复杂的路由配置和组织方式。不过,以上步骤应该可以帮助你开始使用Vue Router进行路由拆分。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值