一、效果

在about页面点击“我的”,路径里传入了参数zhangsan,在“我的”页面里接收传递过来的张三并展现出来。注:标签中传递参数写法

 <vue 5、动态路由-标签上传递参数>

 

 

二、代码结构

注:主要是标红的几个文件

 <vue 5、动态路由-标签上传递参数>

 

 

三、代码

index.js

//引入路由
import {
	createRouter,
	createWebHistory
} from 'vue-router'
import Home from '../views/Home.vue'

//定义路由
const routes = [{
		path: '/',
		name: 'Home',
		component: Home
	},
	{
		path: '/about',
		name: 'About',
		component: () => import('../views/About.vue'),
		children: [{
				path: '',
				component: () => import('../views/AboutNews.vue')
			},
			{
				path: 'news',
				component: () => import('../views/AboutNews.vue')
			},
			{
				path: 'sport',
				component: () => import('../views/AboutSport.vue')
			},
			{
				path: 'me/:userId',
				component: () => import('../views/AboutMe.vue')
			}
		]
	}
]

//创建路由
const router = createRouter({
	//createWebHashHistory hash模式路径前面会多一个#号
	history: createWebHistory(process.env.BASE_URL),
	routes
})

//返回了路由
export default router

 

App.vue

<template>
  <div id="nav">
    <router-link to="/"  replace>Home</router-link> |
    <router-link to="/about"  replace>About</router-link> |
<!-- 	<router-link :to="'/about/me/'+userId">我</router-link> -->
	 
  </div>
  <router-view></router-view>
</template>


<script>
 export default {
   name: 'App',
   data() {
     return {
       userId: 'zhangsan' 
     }
   } 
 }
</script>

 
 <style>
  .router-link-active {
    color: #f00; 
  } 
 
 </style>
 

 

Home.vue

<template>
  <div class="home">
	  <p>Home Page</p>
    <img alt="Vue logo" src="../assets/logo.png">
  </div>
</template>

<script>
</script>

 

About.vue

<template>
  <div class="about">
    <h1>about page</h1>
	
	<div>
		<router-link to="/about/news">新闻</router-link>|
		<router-link to="/about/sport">体育</router-link>|
		<router-link :to="'/about/me/'+userId">我的</router-link>|
	 
		<router-view></router-view>
	</div>
	
  </div>
  
</template>

<script>
 export default {
   name: 'About',
   data() {
     return {
       userId: 'zhangsan' 
     }
   } 
 }
</script>
 

 

AboutNews.vue

<template>
  <div>
    <ul>
      <li>新闻1</li>
      <li>新闻2</li>
      <li>新闻3</li>
      <li>新闻4</li>
    </ul>
  </div>
</template>

<script>
  export default {
    name: "AboutNews"
  }
</script>

<style scoped>

</style>

 

AboutSport.vue

<template>
  <div>
    <ul>
      <li>体育1</li>
      <li>体育2</li>
      <li>体育3</li>
      <li>体育4</li>
    </ul>
  </div>
</template>

<script>
  export default {
    name: "AboutSport"
  }
</script>

<style scoped>

</style>

 

AboutMe.vue

 

<template>
  <div>
     <p>我的主页</p>
	 <p>{{$route.params.userId}}</p>
  </div>
</template>

<script>
  export default {
    name: "AboutMe"
  }
</script>

<style scoped>

</style>

 

四、知识点

$route和$router是有区别的

1、$router为VueRouter实例,想要导航到不同URL,则使用$router.push方法

2、$route为当前router跳转对象里面可以获取name、path、query、params等

 

 

上一篇:drop、truncate和delete的区别


下一篇:mediasoup中router的创建过程