vue3实现父组件传递数据并调用子组件函数
时间: 2023-06-13 19:02:53 浏览: 300
在 Vue3 中,可以通过 ref
和 setup
来实现父组件传递数据并调用子组件函数。
首先,在子组件中定义一个 ref
,用于存储父组件传递的数据:
<template>
<div>{{ data }}</div>
</template>
<script>
import { ref } from 'vue';
export default {
setup(props) {
const data = ref(props.data);
function doSomething() {
// 子组件的函数
}
return {
data,
doSomething
};
}
};
</script>
然后,在父组件中引用子组件,并通过 v-bind
将数据传递给子组件:
<template>
<div>
<ChildComponent :data="dataRef.value" />
<button @click="callChildFunction">调用子组件函数</button>
</div>
</template>
<script>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
setup() {
const dataRef = ref('父组件传递的数据');
function callChildFunction() {
// 调用子组件的函数
ChildComponent.value.doSomething();
}
return {
dataRef,
callChildFunction
};
}
};
</script>
在父组件中,可以通过 ChildComponent.value
来访问子组件中的 ref
对象,从而调用子组件的函数。
相关推荐


















