子
组件里直接调用父组件事件的几种方法
1.在子组件里用$emit向父组件传递一个个事件,父组件监听这个事件就行了。
父组件:
<template>
<div>
<child @father="father"></child>
</div>
</template>
<script>
import child from './components/child';
export default {
components: {
child
},
methods: {
father() {
console.log('这是父组件呀');
}
}
};
</script>
子组件:
<template>
<div>
<button @click="child()">点击</button>
</div>
</template>
<script>
export default {
methods: {
child() {
this.$emit('father');
}
}
};
</script>
2.父组件将方法传入子组件中,子组件直接调用这个方法
父组件:
<template>
<div>
<child :father="father"></child>
</div>
</template>
<script>
import child from './components/child';
export default {
components: {
child
},
methods: {
father() {
console.log('这是父组件呀');
}
}
};
</script>
子组件:
<template>
<div>
<button @click="child()">点击</button>
</div>
</template>
<script>
export default {
props: {
father: {
type: Function,
default: null
}
},
methods: {
child() {
if (this.father) {
this.father();
}
}
}
};
</script>
3.直接在子组件中通过this.$parent.event来调用父组件的方法
父组件:
<template>
<div>
<child></child>
</div>
</template>
<script>
import child from './components/child';
export default {
components: {
child
},
methods: {
father() {
console.log('这是父组件呀');
}
}
};
</script>
子组件:
<template>
<div>
<button @click="child()">点击</button>
</div>
</template>
<script>
export default {
methods: {
child() {
this.$parent.father();
}
}
};
</script>