Vue3路由配置createRouter、createWebHistory、useRouter,useRoute

目录

手动配置Vue-router环境:

组件内部跳转路由、传参useRouter,useRoute


Vue3和Vue2基本差不多,只不过需要将createRoutercreateWebHistoryvue-router中引入,再进行使用。

手动配置Vue-router环境:

1、下载包: npm i vue-router --save或者 npm i vue-router --S    或者用cdn引入

2、创建路由的js文件(路由、子路由、重定向、开启history模式)

      createRouter、createWebHistory

//路由文件
import { createRouter, createWebHistory } from 'vue-router'  //将createRouter、createWebHistory引入vue
const routes = [
  {
    path: '/',  //配置默认路由
    name: 'home', //路由名
    component: () => import("../views/home.vue"), //引入该路由使用的组件
  
  },
  {
    path: '/a',
	
    name: 'a',
    component: () => import('../views/a.vue'),
	redirect: '/a/son1',
	children:[ //配置子路由
		{
		path: '/a/son1', //子路由路径前边必须写父路由路径
		name: 'ason1',
		component: ()=>import("../views/a-son1.vue")	
		}
	]
  },
  {
    path: '/b',
  	
    name: 'b',
    component: () => import('../views/b.vue'),
  	redirect: '/b/son1', //重定向,进入/b路由时默认进入/b/son1
  	children:[ //配置子路由
  		{
  		path: '/b/son1', //子路由路径前边必须写父路由路径
  		name: 'bson1',
  		component: ()=>import("../views/b-son1.vue")	
  		}
  	]
  }
]
const router = createRouter({ //设置为history模式
  history: createWebHistory(),
  routes
})


export default router

3、将配置的路由js文件引入到main.js中

import { createApp } from 'vue'
import App from './App.vue'

const app=createApp(App)

import router from "./router/index.js" //引入配置路由文件
app.use(router)//记得在mount之前调用

app.mount('#app')

4、界面中使用router-view标签显示路由

组件内部跳转路由、传参useRouter,useRoute

vue3中,在组件内部跳转路由 需要使用useRouter,useRoute方法

useRoute相当于以前的this.$route 跳转路由

用法:

<template>
	<h1>aaa</h1>
	<router-view></router-view>
	<button @click="fn">从a路由跳转到b路由</button>
</template>

<script setup>
	import {useRouter} from "vue-router"
	    let router=useRouter() //接收useRouter方法,在vue2中是直接使用router即可
	
		let fn=()=>{
	        
			router.push({path:"/b",query:{name:"小狮子"}}) //path写跳转的路由,同样可以传参
		}
	    
</script>

<style scoped>
	h1{
		width: 400px;
	    height:200px;
		background-color:deeppink;
	}
</style>

useRouter相当于this.$router  接受传参(query、params)

注意:1、请注意params只与name(路由文件里配置的路由name)搭配生效(不能使用path)

        2、只能在setup函数内使用

用法

<template>
	<h2>这是b-son1</h2>
	<button @click="fn">lookquery</button>
</template>

<script setup>
	import {useRoute} from "vue-router" //引入
	let route=useRoute()
	 console.log(route.query)//如果是params传参就用route.params接收

let fn=()=>{  //这不是setup函数内部,是取不到传参的,返回undefined
		let route=useRoute()
		 console.log(route)
	}
	
</script>

<style scoped>
	h2{
		width: 200px;
	    height:100px;
		background-color:aliceblue;
	}
</style>

结合前者代码进行验证,发现下图状况

 当我们进行页面跳转时成功获取了传参,但不在setup函数内使用useRouter是获取不了的

猜你喜欢

转载自blog.csdn.net/m0_63470734/article/details/126995445