Case number one
parent component
<template>
<div>
<div @click="click">点击父组件</div>
<child ref="child"></child>
</div>
</template>
<script>
import child from "./groundCrudeOilImg";
export default {
methods: {
click() {
this.$refs.child.$emit('childMethod','发送给方法一的数据')
this.$refs.child.callMethod()
},
},
components: {
child,
}
}
</script>
Subassembly
<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>
Case 2
parent component
<template>
<div id="app">
<div id="home">
<aaa ref="header"></aaa>
<hr>
首页组件
<button @click="getChildData()">获取子组件的数据和方法</button>
</div>
</div>
</template>
<script>
import aaa from "./aa.vue";
export default {
name: 'App',
data(){
return {
msg:'我是一个首页组件',
title:'首页111'
}
},
components:{
'aaa':aaa
},
methods:{
run(){
alert('我是首页组件的run方法');
},
getChildData(){
alert(this.$refs.header.msg);
this.$refs.header.run()
alert(this.$refs.header.run())
}
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
Subassembly
<template>
<div>
<h2>我是头部组件</h2>
<button @click="getParentData()">获取子组件的数据和方法</button>
</div>
</template>
<script>
export default {
name: 'aa',
data(){
return{
msg:'子组件的msg'
}
},
methods:{
run(){
alert('我是子组件的run方法')
return"我是子组件的run方法"
},
getParentData(){
this.$parent.msg
this.$parent.方法
alert(this.$parent.msg);
this.$parent.run();
}
}
};
</script>
<style lang="scss" scoped>
</style>