vue3 setup父组件调用子组件方法
时间: 2023-05-10 21:01:29 浏览: 130
在Vue3中,使用Composition API和setup()函数可以非常方便地编写组件逻辑。在父组件中调用子组件方法,首先需要在两个组件的代码中分别定义和引入。
在子组件中,我们可以使用ref()函数定义一个响应式的属性或方法,并在template中通过组件名引用这个属性或方法,比如:
```html
<template>
<div>
<button @click="sayHello">Say Hello</button>
</div>
</template>
<script>
import {ref} from 'vue';
export default {
setup() {
const greeting = ref('Hello');
const sayHello = () => {
console.log(greeting.value);
};
return {greeting, sayHello};
}
}
</script>
```
在父组件中,我们需要使用ref或reactive函数创建一个响应式对象,并在template中使用子组件时,通过v-bind将这个对象传递给子组件,比如:
```html
<template>
<div>
<h2>{{message}}</h2>
<child-component v-bind:greeting="greeting" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
import {ref} from 'vue';
export default {
components: {ChildComponent},
setup() {
const message = ref('Hello, Vue3!');
const greeting = ref('');
return {message, greeting};
}
}
</script>
```
在子组件中,我们可以通过props来接收父组件传递的响应式对象,并在方法中对其进行操作,比如:
```html
<template>
<div>
<button @click="sayHello">Say Hello to Parent</button>
</div>
</template>
<script>
import {ref, defineProps} from 'vue';
export default {
props: {
greeting: {
type: Object,
default: () => ({})
}
},
setup(props) {
const sayHello = () => {
console.log(props.greeting.value);
};
return {sayHello};
}
}
</script>
```
这里使用了defineProps函数来定义props,其参数为props的默认值和类型,这样可以让props的类型校验更加严格。
通过以上步骤,我们就可以在父组件中调用子组件的方法了。具体而言,我们可以在父组件的方法中,通过调用子组件的响应式对象来执行子组件中的方法,比如:
```html
<template>
<div>
<h2>{{message}}</h2>
<child-component v-bind:greeting="greeting" ref="childComponent" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
import {ref} from 'vue';
export default {
components: {ChildComponent},
setup() {
const message = ref('Hello, Vue3!');
const greeting = ref('Hi, Child Component!');
const childComponent = ref(null);
const callChildMethod = () => {
childComponent.value.sayHello();
};
return {message, greeting, childComponent, callChildMethod};
}
}
</script>
```
在父组件中,我们通过v-bind将父组件中的greeting属性传递给子组件中的greeting属性,然后在父组件的callChildMethod()方法中,通过ref()函数获取childComponent组件实例,并调用其sayHello()方法,从而实现了父组件调用子组件方法的功能。
总之,在Vue3中,通过setup()函数和响应式对象,可以非常方便地编写组件逻辑,并实现父组件调用子组件方法等复杂功能。