Vue74 路由的props配置

笔记

​ 作用:让路由组件更方便的收到参数

{
   
   
	name:'xiangqing',
	path:'detail/:id',
	component:Detail,

	//第一种写法:props值为对象,该对象中所有的key-value的组合最终都会通过props传给Detail组件
	// props:{a:900}

	//第二种写法:props值为布尔值,布尔值为true,则把路由收到的所有params参数通过props传给Detail组件
	// props:true
	
	//第三种写法:props值为函数,该函数返回的对象中每一组key-value都会通过props传给Detail组件
	props(route){
   
   
		return {
   
   
			id:route.query.id,
			title:route.query.title
		}
	}
}

代码

在这里插入图片描述

Banner.vue

<template>
	<div class="col-xs-offset-2 col-xs-8">
		<div class="page-header"><h2>Vue Router Demo</h2></div>
	</div>
</template>

<script>
	export default {
     
     
		name:'Banner'
	}
</script>

About.vue

<template>
	<h2>我是About的内容</h2>
</template>

<script>
	export default {
     
     
		name:'About',
		/* beforeDestroy() {
			console.log('About组件即将被销毁了')
		},*/
		/* mounted() {
			console.log('About组件挂载完毕了',this)
			window.aboutRoute = this.$route
			window.aboutRouter = this.$router
		},  */
	}
</script>

Detail.vue

<template>
	<ul>
		<li>消息编号:{
  
  {id}}</li>
		<li>消息标题:{
  
  {title}}</li>
	</ul>
</template>

<script>
	export default {
     
     
		name
### Vue3 中路由使用 Props 传递参数Vue3 的路由配置中,`props` 可以用来向目标组件传递静态或动态的数据。这不仅简化了数据传递的过程,也提高了代码的可读性和维护性。 #### 静态 Props 传递 当需要传递固定的参数值时,可以采用对象形式定义 `props` 属性。这种方式适用于那些不需要随着 URL 改变而变化的情况: ```javascript const routes = [ { path: '/example', component: ExampleComponent, props: { a: 100, b: 200, c: 300 } // 固定参数值[^1] } ]; ``` #### 动态 Props 传递 对于依赖于路径参数或其他条件变化的数据,则应考虑使用布尔值或函数来设置 `props`。如果设为 `true`,则会自动将以冒号开头的对象作为 prop 进行绑定;如果是函数,则可以根据当前匹配的结果返回自定义属性对象: ```javascript // 基于路径参数的动态Props { path: '/user/:id', name: 'UserDetail', component: UserDetail, props: true // 自动将URL中的params映射成prop } // 函数式的动态Props { path: '/product/:id', name: 'ProductInfo', component: ProductInfo, props(route) { return { id: route.params.id, queryParam: route.query.q || '' }; } } ``` 上述例子展示了如何利用不同的方式实现从路由到组件之间的灵活数据传输[^4]。 #### 实际应用场景下的代码示例 下面是一个完整的实例,展示了一个简单的博客文章详情页是如何接收来自父级路由的 ID 并据此加载相应的内容: ```html <!-- BlogPost.vue --> <template> <div v-if="post"> <h1>{{ post.title }}</h1> <p>{{ post.content }}</p> </div> </template> <script setup> import { ref, onMounted } from 'vue'; import axios from 'axios'; const props = defineProps(['postId']); let post = ref(null); onMounted(() => { fetchPost(); }); async function fetchPost() { const response = await axios.get(`/api/posts/${props.postId}`); post.value = response.data; } </script> ``` 在此案例中,每当访问 `/blog/123` 类似的链接时,都会触发相应的请求去获取指定编号的文章信息并渲染出来[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值