I need a way to communicate from a child component to its parent in VueJS without using Vuex. I find Vuex too complex for my current level of understanding with VueJS. My project involves single file components.
Here is the code snippet for the child component (child.vue):
<script>
export default {
name: 'ChildComponent',
methods: {
// ajax post here ...
if (response.data.status === 'accepted'){
this.$emit('send-data', 'accepted')
}
}
}
And here is the code snippet for the parent component (parent.vue):
<script>
import ChildComponent from './ChildComponent.vue'
export default {
name: 'Parent',
data () {
return {
stage: 1
}
},
components: {
ChildComponent
},
created() {
// How can I replace 'events' with $on in a single file component and listen for events after all components have been created?
this.$on('send-data', function(dataResponse) {
if (dataResponse === 'accepted'){
this.stage = 2
}
})
}
}
I have come across examples in the VueJS documentation that use eventHub like this:
var eventHub = new Vue()
created() {
eventHub.$on('add-todo', this.addTodo)
eventHub.$on('delete-todo', this.deleteTodo)
},
However, I want to be able to listen to events at any time, not just during creation. How can I replace the parent's 'events' with a $on function?