I have a windows.addEventListener that triggers an API call. I need to pass a name from the api call to the parent component to display it as a title on a dashboard. How can I emit the data to my parent component
child:
<sankey-input-details v-if="!tableLoading" :cardListData="dataFromApi"/>
async apiData() {
const nodeData = this.dateRange
? await get('nodeData', {
dateStart: this.dateRange[0],
dateEnd: this.dateRange[1],
nodeName: this.nodeName
}) : await get('nodeData', {
nodeName: this.nodeName
});
nodeData[0].name <-------- data to be emitted.
this.tableLoading = false;
parent:
props: {
title: String,
cardListData: Array
},
CodePudding user response:
https://vuejs.org/guide/components/events.html#emitting-and-listening-to-events
The $emit() method is also available on the component instance as this.$emit():
so in your method:
this.$emit('emitName', nodeData[0].name)
CodePudding user response:
Here you go, You can emit the event to parent from child by using $emit
function.
Vue.component('child', {
props: ['childmsg'],
template: '<p>{{ childmsg }}</p>',
mounted() {
// Just for the demo I am emiting the value directly but you can replace that with your API call code.
const nodeData = [{
name: 'Parent Header'
}];
this.$emit('headername', nodeData[0].name);
}
});
var app = new Vue({
el: '#app',
data: {
headerText: null
},
methods: {
showName(e) {
this.headerText = e;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<h1>{{ headerText }}</h1>
<child childmsg="This is a child component" @headername="showName"></child>
</div>