vue3defineprops属性简介

在子组件里不需要引入defineProps就可调用该函数去接收父组件传来的属性。

这里需要注意!!这是definePropsAPI是一个函数,它的返回值就是父亲传来的属性。

这里变量名不一定非得是props,js可并没有规定不允许汉字作为变量名哦 

在 单文件组件中,向组件传递数据,下面以 blog(父组件)和article(子组件)为例。

1.例子

在blog.vue中,先引入article。

// Blog.vue
<template>
	<Aritice :title="AriticeItem.title" :info="AriticeItem.info" :author="AriticeItem.author">
	 <!-- v-bind ( : ) ,父组件将值绑定到子组件上 -->
    </Aritice>
</template>
<script setup>
	import { reactive } from 'vue';
	import Article from '@/components/Article.vue';
	const AriticeItem = reactive({
		title: '文章标题',
	    info: '文章内容',
	    author: 'X',
	  });
</script>

//Article.vue
<template>
	<section>
  		<p>{{ title }}</p>
    	<p>{{ info }}</p>
    	<p>{{ author }}</p>
	</section>
</template>
<script setup>
	const props = defineProps({
		title: String,
		info: String,
		author: String,
	});// 对象形式声明 props
	// 等价于以 字符串数组声明 props
	//const props = defineProps(['title', 'info', 'author']);
	// 如果在setup中使用则直接 props.title
</script>
<style></style>

2.说明

  • 对象形式声明:key 是对应的名称。value在上面的示例中是prop中对应的类型。value的具体格也可以是一个对象,常用的属性如下

{
	type:String ,// 如果可能存在多个类型,则可以写成 [String,Number]
	default:'默认值',
	required: true// 是否必传 ,在不声明为true 的情况下,所有prop 默认为非必填。
}
// 上面的title 字段展开则为
title:{
	type:String
}
  • 字符串数组声明:数组的每一项字面量就为prop对应的名称。

3 使用

在template 模版中,直接使用 defineProps() 声明过后的名称。
在setup中(以1.例子中的代码为例),只需要直接 props.title 就可以获取到title 对应的值。

props一般是单向的,在子组件中不应该对 props 进行修改。如果需要在子组件中对props进行处理,应当使用ref(初始值为props的值):

const formatTitle = ref(props.title)
//这样,子组件中后续对 formatTitle 的修改,就与原props.title 无关联了

如果子组件中对数据更新,确实需要修改原数据,那么应当通知父组件或者props传入的地方,对数据进行调整(涉及到组件的事件)

在上述例子中,props是一个对象,并且每个属性都要传递到子组件中,可以使用不指定参数的,v-bind 方法:

 <Aritice v-bind="AriticeItem"></Aritice>
 <!-- 也可 <Aritice :="AriticeItem"></Aritice>-->
 <!-- 子组件中的声明不需要改变,但是需要将用到的AriticeItem的属性,都通过 defineProps 显示出来-->

每一个在组件上 v-bind( : ) 的值,都不应该重复(无参数的v-bind重复出现,编辑器会报错)。如果出现同名的 v-bind 绑定,后绑定会覆盖前一个。
需要注意的是,props的名称不应该与组件中的其它属性名称重复。

选项式props,emits-> 组合式props,emits:

比如,下面这种 选项API 方式:

        props: {
    name: {
      type: String,
      required: true.
    }
  },
  emits: ['someEvent', 'increaseBy']

我们将它转成 组合API 方式:

        const props = defineProps<{
  name: string;
 }>();
 const emit = defineEmits<{
  (event: 'someEvent): void;
  (event: 'increaseBy', value: number): void;
 }>();

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值