vue3子组件调用父组件的3种方法
时间: 2023-12-27 14:23:06 浏览: 35
以下是Vue3子组件调用父组件的三种方法:
1. 使用props向子组件传递方法,子组件通过$emit触发父组件的方法。
父组件:
```html
<template>
<div>
<child :fatherMethod="fatherMethod"></child>
</div>
</template>
<script>
import child from './components/childcomponent';
export default {
components: {
child
},
methods: {
fatherMethod() {
console.log('父组件方法');
}
}
};
</script>
```
子组件:
```html
<template>
<div>
<button @click="childMethod">触发父组件方法</button>
</div>
</template>
<script>
export default {
props: {
fatherMethod: {
type: Function,
required: true
}
},
methods: {
childMethod() {
this.$emit('fatherMethod');
}
}
};
</script>
```
2. 使用$parent访问父组件的方法。
父组件:
```html
<template>
<div>
<child></child>
</div>
</template>
<script>
import child from './components/childcomponent';
export default {
components: {
child
},
methods: {
fatherMethod() {
console.log('父组件方法');
}
}
};
</script>
```
子组件:
```html
<template>
<div>
<button @click="$parent.fatherMethod()">触发父组件方法</button>
</div>
</template>
<script>
export default {
methods: {
childMethod() {
this.$parent.fatherMethod();
}
}
};
</script>
```
3. 使用provide/inject实现父子组件通信。
父组件:
```html
<template>
<div>
<child></child>
</div>
</template>
<script>
import child from './components/childcomponent';
export default {
components: {
child
},
provide: {
fatherMethod: () => {
console.log('父组件方法');
}
}
};
</script>
```
子组件:
```html
<template>
<div>
<button @click="childMethod">触发父组件方法</button>
</div>
</template>
<script>
export default {
inject: ['fatherMethod'],
methods: {
childMethod() {
this.fatherMethod();
}
}
};
</script>
```