<!-- ParentComponent.vue -->
<template>
<div class="father">
<h3>父组件</h3>
<h4>我的车:{{ car }}</h4>
<h4>儿子给的玩具:{{ toy }}</h4>
<Child :car="car" :getToy="getToy"/>
</div>
</template>
<script setup lang="ts" name="Father">
import Child from './Child.vue'
import { ref } from "vue";
// 数据
const car = ref('奔驰')
const toy = ref()
// 方法
function getToy(value:string){
toy.value = value
}
</script>
在父组件中,我们首先引入了子组件 Child。然后,通过 :car=“car” 和 :getToy=“getToy”,我们将父组件的数据 car 和方法 getToy 传递给了子组件。这样,子组件就可以在其内部访问到这些属性和方法。
接下来,让我们看一下子组件向父组件传递事件的部分代码:
<!-- ChildComponent.vue -->
<template>
<div class="child">
<h3>子组件</h3>
<h4>我的玩具:{{ toy }}</h4>
<h4>父给我的车:{{ car }}</h4>
<button @click="giveToyToFather">玩具给父亲</button>
</div>
</template>
<script setup lang="ts" name="Child">
import { ref } from "vue";
const toy = ref('奥特曼')
// 接收父组件传递过来的属性和方法
const { car, getToy } = defineProps(['car', 'getToy']);
// 方法
function giveToyToFather() {
getToy(toy.value); // 触发父组件的方法,将玩具传递给父组件
}
</script>
首先,让我解释一下defineProps([‘car’,‘getToy’])的含义。在子组件中,defineProps 函数用于声明组件接收的属性,即 props。在这个例子中,[‘car’,‘getToy’] 是一个字符串数组,指定了子组件需要接收的两个属性名:car 和 getToy。通过调用 defineProps([‘car’,‘getToy’]),Vue 3 将会自动将这些属性传递给组件,并在组件中提供对应的响应式数据。
在子组件中,我们首先使用 defineProps([‘car’, ‘getToy’]) 声明了需要接收的属性和方法。然后,通过 const { car, getToy } = defineProps([‘car’, ‘getToy’]);,我们将父组件传递过来的 car 属性和 getToy 方法解构赋值给了子组件中的变量。最后,当点击按钮时,我们调用 giveToyToFather 方法,该方法会触发父组件的 getToy 方法,并将玩具传递给父组件。
这样,就完成了父组件向子组件传递属性值,以及子组件向父组件传递事件的功能。