组件中的Props

        在项目开发中,在开发某些界面时,我们可以将一些代码封装成组件来简化代码。但是,如果某些情况下组件中的某些属性不是一成不变的(比如一个头像+姓名的组件,每次使用时都需要改变其图像src和姓名字符串),我们就可以使用Props

我们要使用Props,我们需要先在组件中声明注册

        例如,一个商品图片+名字的组件,我们每次使用时都要向其中传入一个图像src和一个名字字符串。

组件代码如下:

<template>
	<view>
		<image :src="pic"></image>
		<view>{{goods_name}}</view>
	</view>
</template>

<script setup>
	defineProps(['pic','goods_name'])
</script>

<style lang="scss">

</style>

在界面中使用组件:

<view>
		<blog_Props pic="../../static/ai.jpg" goods_name="Picture1"></blog_Props>
</view>

效果如下:

        如果需要在组件中“改变”传递过来的值,我们不能直接改变Props中的内容,我们需要这样操作,然后就可以通过computed来改变呈现在页面上的样子了。

<template>
	<view>
		<image :src="props.pic"></image>
		<view>{{props.goods_name}}</view>
	</view>
</template>

<script setup>
const props = defineProps(['pic','goods_name'])
</script>

<style lang="scss">

</style>

Props的几种声明注册的方式

  声明注册为一个数组。

<script setup>
const props = defineProps(['pic','goods_name'])
</script>

  另一种方式,这样写可以方便的设置默认值等属性,当页面没有向组件传递某个参数时,组件将使用默认值。

<script setup>
// const props = defineProps(['pic','goods_name'])
const props = defineProps({
	pic:{
		type:String,
		defaut:"../../static/logo.jpg"
	},
	goods_name:{
		type:String,
		defaut:"None"
	}
})
</script>

  也可以向子组件中传递一个对象,只需要将type后的属性改成Object即可。但是在写默认值时需要这么写。

<script setup>
// const props = defineProps(['pic','goods_name'])
const props = defineProps({
	pic:{
		type:String,
		defaut:"../../static/logo.jpg"
	},
	goods_name:{
		type:String,
		defaut:"None"
	},
	obj_test:{
		type:Object,
		defaut(){
			return {pic:"../../static/logo.jpg",name:"None"}
		}
	}
})
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

YoloMari

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值