Passing data between Vue components using mitt

214 Views Asked by At

I have a simple Vue.j application with a navigation bar.

The App.vue looks like this:

<template>
  <div>
    <h1>Application using Vue Router</h1>
    <nav>
      <ul>
        <li>
          <router-link to="/">Home</router-link>
        </li>
        <li>
          <router-link to="/about">About</router-link>
        </li>
        <li>
          <router-link to="/contact">Contact</router-link>
        </li>
      </ul>
    </nav>
    <hr />
    <router-view></router-view>
  </div>
</template>

The main.js file loooks like this:

import { createApp } from 'vue'
import App from './App.vue'
import './index.css'
import router from './router'

import mitt from 'mitt'; // Import mitt
const emitter = mitt(); // Create an emitter

const app = createApp(App);
app.use(router);

app.config.globalProperties.emitter = emitter; // Emitter is now available in all components

app.mount('#app');

The About.vue component looks like this:

<template>
  <div>
    <h2>About Page</h2>
    <p>Welcome to the About page!</p>
    <p>You can send data to the home page from here using the MITT library</p>
    <input type="text" v-model="msg">
    <button @click="sendData">Send Data to Home</button>
  </div>
</template>

<script>
  export default {
    name: 'About',
    data() {
      return {
        msg: ''
      }
    },
    methods: {
      sendData() {
        this.emitter.emit('emitter', { message: this.msg });
      }
    }
  }
</script>

The Home.vue component looks like this:

<template>
  <div>
    <h2>Home Page</h2>
    <p>Welcome to the Home page!</p>
    <h2>{{ msg }}</h2>
  </div>
</template>

<script>
  export default {
    name: 'Home',
    data() {
      return {
        msg: null
      }
    },
    mounted() {
      this.$root.emitter.on('emitter', (data) => {
        this.msg = data.message;
        console.log(this.msg);
      })
    }
  }
</script>

I want to send data from About to Home using mitt. The data is sent correctly but when I change the route, from About to Home, the variable msg in Home is not updated in the view.

0

There are 0 best solutions below