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>

页面效果:

相关推荐
墨渊君14 分钟前
React Native 跨平台组件库实践: GlueStack UI 上手指南
前端
晓得迷路了22 分钟前
栗子前端技术周刊第 84 期 - Vite v7.0 beta、Vitest 3.2、Astro 5.9...
前端·javascript·vite
独立开阀者_FwtCoder25 分钟前
最全301/302重定向指南:从SEO到实战,一篇就够了
前端·javascript·vue.js
Moment34 分钟前
给大家推荐一个超好用的 Marsview 低代码平台 🤩🤩🤩
前端·javascript·github
小满zs38 分钟前
Zustand 第三章(状态简化)
前端·react.js
普宁彭于晏40 分钟前
元素水平垂直居中的方法
前端·css·笔记·css3
恋猫de小郭1 小时前
为什么跨平台框架可以适配鸿蒙,它们的技术原理是什么?
android·前端·flutter
云浪1 小时前
元素变形记:CSS 缩放函数全指南
前端·css
明似水1 小时前
用 Melos 解决 Flutter Monorepo 的依赖冲突:一个真实案例
前端·javascript·flutter
独立开阀者_FwtCoder1 小时前
stagewise:让AI与代码编辑器无缝连接
前端·javascript·github