Vue父子组件属性传递实现方法详解

前言

这节我们主要从案例出发,用Vue3的写法写父子组件之间的属性传递。

组件之间属性的传递

我们定义一个Rate组件,具有以下功能:

  • 接收来自外部组件传入的参数,starCount代表星星个数。color代表星星颜色。
  • 需要根据传入星星的个数,展示对应数量的星星。

父组件传递属性给子组件

那么在编写组件的时候,我们需要注意什么?

  • 我们可以使用defineProps来规范传递数据的格式。可以结合withDefaults来进行默认值的赋值。
  • 如果是响应式数据的传递,在传递给子组件的时候,需要添加前缀 :。如果是常量,则不用。

我们在components目录下创建完Rate.ts文件后。完整代码如下:

<template>
 <div :style="fontstyle">
 {{ rate }}
 </div>
</template>
<script setup lang="ts">
import { computed, defineProps, withDefaults } from "vue";
// 定义父组件传入的参数类型
interface Props {
 starCount: number;
 color: string;
}
// 规定传值类型以及赋上默认值
let props = withDefaults(defineProps<Props>(), {
 starCount: 0,
 color: "blue",
});
// 凡是计算有关的,我们都用computed来包装
const rate = computed(() =>
 "★★★★★☆☆☆☆☆".slice(5 - props.starCount, 10 - props.starCount)
);
const fontstyle = computed(() => {
 return `color:${props.color};`;
});
</script>

外部组件调用如下:

<template>
 <Rate starCount="3"></Rate>
 <Rate starCount="4" color="red"></Rate>
 <Rate starCount="1" color="green"></Rate>
</template>
<script setup>
import Rate from "./components/Rate.vue";
</script>

最终效果如下:

子组件传递属性给父组件

我们在编写组件的时候,我们需要注意什么?

  • 子组件:需要通过defineEmits函数,注册一个自定义事件或者其他事件,例如click事件。然后手动触发emit函数,调用该自定义事件,并传递参数。
  • 父组件:引用子组件的时候,通过v-on绑定一个函数,指向子组件里面定义的事件。注意:v-on的效果等同于@符号。

定义一个子组件Son

<template>
 <div style="margin: 10px; border: 2px solid red">
 我是子组件
 <button @click="transValue" style="margin: 5px;background:#caca88">传值给父组件</button>
 </div>
</template>
<script setup lang="ts">
import { ref } from "vue";
// 定义所要传给父组件的值
const num = ref<number>(0);
// 使用defineEmits注册一个自定义事件
const emit = defineEmits(["getValue"]);
// 点击事件触发emit,去调用我们注册的自定义事件getValue,并传递value参数至父组件
const transValue = () => {
 num.value++;
 emit("getValue", num.value);
};
</script>

父组件Father

<template>
 <div class="fa">
 <div style="margin: 10px;">我是父组件</div>
 父组件接收子组件传的值:{{sonMessage}}
 <Son @getValue="getSonValue"></Son>
 <!-- <Son v-on:getValue="getSonValue"></Son> -->
 </div>
</template>
<script setup lang="ts">
import Son from './Son.vue'
import {ref} from "vue";
const sonMessage = ref<String>('0')
const getSonValue = (value: String) => {
 sonMessage.value = value
}
</script>
<style scoped>
.fa{
 border: 3px solid cornflowerblue;
 width: 400px;
 text-align: center;
}
</style>

运行效果如下:

作者:Zong_0915原文地址:https://blog.csdn.net/Zong_0915/article/details/128922015

%s 个评论

要回复文章请先登录注册