1、通过 ref 直接调用子组件的方法。
父组件
<template>
<div>
<button @click="handleClick">点击调用子组件方法</button>
<Child ref="child"/>
</div>
</template>
<script>
import Child from './child';
export default {
methods: {
handleClick() {
this.$refs.child.childFun();
},
},
}
</script>
子组件
<template>
<div>我是子组件</div>
</template>
<script>
export default {
methods: {
childFun() {
console.log('我是子组件的方法');
},
},
};
</script>
2、通过组件的$emit、$on方法。
父组件
<template>
<div>
<button @click="handleClick">点击调用子组件方法</button>
<Child ref="child"/>
</div>
</template>
<script>
import Child from './child';
export default {
methods: {
handleClick() {
this.$refs.child.$emit("childMethod");
},
},
}
</script>
子组件
<template>
<div>我是子组件</div>
</template>
<script>
export default {
mounted() {
this.$nextTick(function() {
this.$on('childMethod', function() {
console.log('我是子组件方法');
});
});
},
};
</script>