VUE父元件呼叫子元件方法
阿新 • • 發佈:2020-10-20
父元件
<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>