方法一:
//父组件中

引入子组件 然后点击调用子组件方法
<template>
<div class="container">
<h1 @click="handleClick" style="text-align: center">Musxc</h1>
<LineChart ref="child" ></LineChart>
</div>
</template>
<script>
import LineChart from "../components/LineChart.vue";
export default {
components: {
LineChart,
},
methods: {
handleClick() {
this.$refs.child.sing();
},
},
};
</script>
//子组件中

我是子组件

export default {
methods: {
sing() {
console.log('我是子组件的方法');
},
},
};
成功的调用了子组件的方法

方法二:通过组件的$emit、$on方法;
//父组件中
点击调用子组件方法
import Child from './child';
export default{ methods: { handleClick() { this.$refs.child.$emit("childmethod") //子组件$on中的名字 },
},
}//子组件中
我是子组件
export default {
mounted() {
this.$nextTick(function() {
this.$on('childmethods',function() {
console.log('我是子组件方法');
});
});
},
};
网友评论