这节我们主要从案例出发,用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>
运行效果如下: