1. 程式人生 > 實用技巧 >vue 父元件呼叫子元件的方法

vue 父元件呼叫子元件的方法

在父元件中:


<template>
    <div>
        <div @click="click">點選父元件</div>
        <child ref="child"></child>
    </div>
</template>

<script>
    import child from "./child";
    export default {
        methods: {
            click() {
                this
.$refs.child.$emit('childMethod','傳送給方法一的資料') // 方法1:觸發監聽事件 this.$refs.child.callMethod() // 方法2:直接呼叫 }, }, components: { child, } } </script> 來源:簡書
子元件中:


<template>
    <div>子元件</div>
</template>

<script
> export default { mounted() { this.monitoring() // 註冊監聽事件 }, methods: { monitoring() { // 監聽事件 this.$on('childMethod', (res) => { console.log('方法1:觸發監聽事件監聽成功') console.log(res) }) }, callMethod() { console.log(
'方法2:直接呼叫呼叫成功') }, } } </script> 來源:簡書