如何进行父子组件传递属性值及方法调用?
prop
: 父组件通过prop
将数据传递给子组件,子组件通过defineProps
接收。
ref
: 父组件通过ref
获取子组件的实例,子组件通过defineExpose
暴露方法或属性供父组件调用。
一.父子组件之间传递属性值:
下面是父传子的典型例子:
1.使用 defineProps
接收父组件传递的属性:
defineProps
是 Vue 3 组合式 API 中用于定义和接收组件 props
的工具。
// 子组件(Child.vue)
<script lang="ts" setup>
import { defineProps } from "vue";
// 定义 props 类型并接收父组件传递的数据
defineProps<{
list: HotItem[]; // 父组件传递的数组
}>();
</script>
<template>
<div>
<ul>
<!-- 遍历父组件传递过来的 list 数据 -->
<li v-for="(item, index) in list" :key="index">
{{ item.name }}
</li>
</ul>
</div>
</template>
子组件中,defineProps
定义了接收的 props
数据名称和类型。例如,子组件 Child.vue
定义了一个名为 list
的 prop
:
<script lang="ts" setup>
defineProps<{
list: string[]; // 子组件声明接收一个名为 "list" 的字符串数组
}>();
</script>
2.父组件传递数据给子组件:
在父组件中,通过绑定 list
属性,将数据传递给子组件。
<script lang="ts" setup>
import Child from "./Child.vue";
// 模拟传递给子组件的数据
const hotList = [
{ name: "Item 1", type: "A" },
{ name: "Item 2", type: "B" },
{ name: "Item 3", type: "C" },
];
</script>
<template>
<div>
<!-- 将 hotList 作为 props 传递给子组件 -->
<!-- list 是子组件定义的 prop 名称 -->
<Child :list="hotList" />
</div>
</template>
在父组件中,使用
:list="parentList"
的形式将父组件的数据parentList
绑定给子组件的list
。
这意味着:
- 子组件的
list
将接收到hotList
的值。hotList
的值发生变化时,子组件中的list
也会自动更新。
二.子组件向父组件暴露方法:
Vue 3 提供的 defineExpose
可以用来将子组件的方法或数据暴露给父组件,方便父组件直接调用子组件的逻辑。
1.子组件暴露方法:
在子组件中,通过 defineExpose
将方法 getMore
暴露给父组件。
<script lang="ts" setup>
import { ref } from "vue";
// 定义并暴露的方法
const getHomeGoodsGuessLikeData = () => {
console.log("加载更多数据...");
};
// 重置数据
const resetData = () => {
console.log("重置数据");
}
// 暴露方法给父组件
defineExpose({
getMore: getHomeGoodsGuessLikeData, // 替换方法名
resetData,
});
</script>
2.父组件调用子组件方法:
父组件通过 ref
获取子组件实例,并调用子组件暴露的方法。
<script lang="ts" setup>
import { ref } from "vue";
import Child from "./Child.vue";
// 定义子组件的引用
const childRef = ref<InstanceType<typeof Child>>();
// 定义触底加载逻辑
const onScrollToLower = () => {
childRef.value?.getMore(); // 调用子组件暴露的 getMore 方法
};
</script>
<template>
<div>
<!-- 将子组件绑定到 ref 上 -->
<Child ref="childRef" />
<button @click="onScrollToLower">触底加载</button>
</div>
</template>
typeof
和InstanceType
的区别:1.
typeof
操作符用于获取某个值或对象的类型。如果你对一个类使用typeof
,它会返回类的构造函数类型,而不是类实例的类型。
typeof XtxGuess
:返回的是XtxGuess
类的构造函数类型,也就是一个类型签名,代表的是如何实例化一个XtxGuess
类。type XtxGuessConstructor = typeof XtxGuess; // XtxGuessConstructor 是构造函数类型
2.
InstanceType<T>
用于从类的构造函数类型T
中获取类的实例类型。通过InstanceType
,我们可以获得类实例的具体类型(包括属性和方法),而不是构造函数本身。type XtxGuessInstance = InstanceType<typeof XtxGuess>;