Vue3 父子组件数据传递:子组件获取ID传给父组件并获取数据
在 Vue3 中,可以使用 Props 和 emit 来实现父子组件之间的数据传递。
首先,在子组件 B 中,获取数据后,通过 emit 方法将 ID 值传递给父组件 A:
// 子组件 B 中获取数据后
const id = responseData.id;
this.$emit('update:id', id);
然后,在父组件 A 中,使用 Props 来接收子组件 B 传递的 ID 值,并在 ID 值发生变化时,调用方法获取相应的数据:
<template>
<div>
<ChildB @update:id="handleIdUpdated" />
<!-- 根据 ID 获取数据 -->
<div v-if="data">{{ data }}</div>
</div>
</template>
<script>
import ChildB from './ChildB.vue';
export default {
components: {
ChildB,
},
props: {
id: {
type: Number,
default: 0,
},
},
data() {
return {
data: null,
};
},
methods: {
async getData() {
const response = await fetch(`url?id=${this.id}`);
this.data = await response.json();
},
handleIdUpdated(id) {
this.id = id;
this.getData();
},
},
};
</script>
在父组件 A 的模板中,将子组件 B 引入,并监听子组件 B 触发的update:id 事件。当子组件 B 传递 ID 值时,会调用handleIdUpdated 方法,该方法将 ID 值赋给id 属性,并调用getData 方法获取相应的数据。
这样,在子组件 B 中获取数据后,父组件 A 就可以根据 ID 访问接口获取数据了。
原文地址: https://www.cveoy.top/t/topic/lAXA 著作权归作者所有。请勿转载和采集!