I have a click event and with this click event I want to call function/methods which is in parent component. So the click event in my child component:
<button @click.native="addNew" />
Here is my method:
methods: {
addNew() {
this.$parent.addNew();
},
},
Ad I want to call this function in my parent component:
addNew() {
this.$emit('open');
},
But I a getting an error like: this.$parent.addNew is not a function. How can I fix it?
CodePudding user response:
Based on $emit event in Vue.js: https://vuejs.org/guide/components/events.html
When you emit an event like this: $emit('someEvent'), the parent someEvent
function will fire (and also you can pass some parameters).
So you must listen to the 'someEvent' function in parent.
EDIT: this link would be a good example: https://learnvue.co/tutorials/vue-emit-guide
CodePudding user response:
Here is a basic example working with events
Child.vue
<template>
<button @click="$emit('childClick')">click me</button>
</template>
Parent.vue
<script setup>
import { ref } from 'vue'
import Child from './Child.vue'
function onChildClick(){
console.log("child has clicked")
}
</script>
<template>
<Child @childClick="onChildClick"></Child>
</template>