One of the key challenges I encountered was establishing communication between components within the same hierarchy. To address this issue, I opted for an Event Bus approach outlined in the Vue.js documentation:
https://v2.vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication
To implement this, I created a new instance of Vue named EventBus:
// EventBus.js
import Vue from 'vue'
export default new Vue()
This EventBus was then globally included in my main Vue instance:
// main.js
import EventBus from './EventBus'
import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false
Vue.prototype.$bus = EventBus
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
template: '<App/>',
components: { App }
})
By using this setup, I could emit events within components and listen for them across other components in the same hierarchy, like demonstrated below:
// Login.Vue
import axios from 'axios'
export default {
name: 'login',
data () {
let data = {
form: {
email: '',
password: ''
}
}
return data
},
methods: {
login () {
axios.post('http://rea.app/login', this.form)
.then(response => {
let responseData = response.data.data
this.$localStorage.set('access_token', responseData.token)
this.$bus.$emit('logged', 'User logged')
this.$router.push('/')
})
.catch(error => {
if (error.response) {
console.log(error.response.data)
console.log(error.response.status)
console.log(error.response.headers)
}
})
}
}
}
In another component, listening to these emitted events can be achieved by setting up a listener in the create method:
// NavBar.js
export default {
template: '<Navigation/>',
name: 'navigation',
data () {
return {
isLogged: this.checkIfIsLogged()
}
},
created () {
this.$bus.$on('logged', () => {
this.isLogged = this.checkIfIsLogged()
})
}
}
I believe this can serve as a helpful reference for similar scenarios.