vue3 router路由传参给组件示例代码

components/HelloWorld.vue

html 复制代码
<script setup>
import { ref } from 'vue'

import {useRoute} from 'vue-router'

const route = useRoute();

const query = route.query
// console.log(query)

</script>

<template>
	<router-link :to="{ 
		path: '/hello/person', 
		query: { id: 1, title: '跳转'} 
		}"><!--也可以采用param传参 -->
		跳转
		</router-link>
	<router-view/>
</template>
<style scoped>
a {
  color: #42b983;
}
</style>

routre/index.js

typescript 复制代码
import Person from '../components/Person.vue'

import HelloWorld from '../components/HelloWorld.vue'

import {createRouter,createWebHistory} from 'vue-router'

import VueTwo from '../components/Vue.vue'

const router = createRouter({
	history:createWebHistory(),
	routes:[
		{
			path:'/hello',
			component:HelloWorld,
			children:[
				{
					path:'/hello/person',
					component:Person
				}
			]
		},
		{	//第二种传参形式2
			path:'/vue2',
			component:VueTwo,
			// props: (route) => ({ id: 1, title: 2, content:3 })
			props(route){
				return ({ id: 1, title: 2, content:3 })
			}
		}
	]
})

export default router

components/person.vue

html 复制代码
<template>
	<div class="ttt">
		<h2>路由给到的数据:{{query}}</h2>
	</div>
</template>

<script setup lang="ts" name="testName">
	import { useRoute } from 'vue-router'
	
	const route = useRoute()
	console.log("person.vue页面获取参数:"+JSON.stringify(route.query))
</script>

<style>
	.ttt{
		color:red
	}
</style>

页面效果:

Vue.vue

html 复制代码
<template>
	<div>
		<h2>{{nameAll}}</h2>
		<h2>{{method}}</h2>
		<h2>{{tt()}}</h2>
		<h2>{{firstName}}</h2>
		<h2>更新后赋值数据:{{lastName}}</h2>
		<h2>赋值数据:{{writeValue}}</h2>
		<button @click="tt">vue2数据更新</button>
	</div>
</template>

<script lang ='ts' name='VueTwo'>
	export default{
		data(){
			return {
				firstName:"wu",
				lastName:"liuqi"
			}
		},
		props: ['id', 'title', 'content'],
		mounted(){
			console.log('ID:', this.id);
			console.log('Title:', this.title);
			console.log('Content:', this.content);
		},
		computed:{
			nameAll:function(){
				return this.firstName + this.lastName
			},
			method(){
				return 111
			},
			writeValue:{
				get(){
					return this.firstName + this.lastName
				},
				set(value){
					this.lastName = value
					return value
				}
			}
		},
		methods:{
			tt(){
				this.writeValue = "alilailail"
			}
		}
	}
</script>

<style>
</style>

页面效果:

相关推荐
老坛00111 分钟前
2025决策延迟的椭圆算子分析:锐减协同工具的谱间隙优化
前端
老坛00112 分钟前
从记录到预测:2025新一代预算工具如何通过AI实现前瞻性资金管理
前端
今禾15 分钟前
" 当Base64遇上Blob,图像转换不再神秘,让你的网页瞬间变身魔法画布! "
前端·数据可视化
华科云商xiao徐19 分钟前
高性能小型爬虫语言与代码示例
前端·爬虫
十盒半价20 分钟前
深入理解 React useEffect:从基础到实战的全攻略
前端·react.js·trae
攀登的牵牛花21 分钟前
Electron+Vue+Python全栈项目打包实战指南
前端·electron·全栈
iccb101321 分钟前
我是如何实现在线客服系统的极致稳定性与安全性的
前端·javascript·后端
一大树22 分钟前
Vue3祖孙组件通信方法总结
前端·vue.js
不要进入那温驯的良夜23 分钟前
跨平台UI自动化-Appium
前端
海底火旺23 分钟前
以一个简单的React应用理解数据绑定的重要性
前端·css·react.js