vue中子组件如何使用父组件中mounted()的方法,写一个demo
时间: 2024-04-29 15:24:37 浏览: 17
可以使用$emit()方法,将子组件中需要调用父组件mounted()中方法的事件触发并传递参数,然后在父组件中通过在template中绑定子组件的自定义事件,即@自定义事件名="方法名",在父组件中定义相应的方法,并在其中调用刚刚传递过来的参数。具体实现如下所示:
父组件:
```
<template>
<div>
<child-component @callParentMethod="handleCallParentMethod"></child-component>
</div>
</template>
<script>
import ChildComponent from '@/components/ChildComponent.vue'
export default {
components: {
ChildComponent
},
methods: {
handleCallParentMethod (param) {
// 执行父组件中的方法
this.someMethod(param)
},
someMethod (param) {
console.log('父组件执行mounted方法,并传入参数:',param)
}
}
}
</script>
```
子组件:
```
<template>
<div>
<button @click="callParentMethod">触发父组件中的mounted方法</button>
</div>
</template>
<script>
export default {
methods: {
callParentMethod () {
// 触发父组件中的方法
this.$emit('callParentMethod', 'yourParam')
}
}
}
</script>
```
这样,当子组件中的按钮被点击后,就能够执行父组件中的方法了。