Vuejs Share Data Between Components

Just keep in mind, the rule of thumb is using props to pass data in a one-way flow

props down, events up.
https://v2.vuejs.org/v2/guide/components.html#Composing-Components

Quick solution:

Global event bus to post messages between your <App/> and <Sidekick/> components.

https://v2.vuejs.org/v2/guide/components.html#Non-Parent-Child-Communication

Long term solution:

Use a state management library like vuex to better encapsulates data in one place (a global store) and subscribe it from your components tree using import { mapState, mapMutations } from 'vuex'


When you have parent-child communication, the best and recommended option is to use props and events. Read more in Vue docs


When want to have shared state between many components the best and recommended way is to use Vuex.


If you want to use simple data sharing you can use Vue observable.

Simple example: Say that you have a game and you want the errors to be accessible by many components. (components can access it and manipulate it).

errors.js

import Vue from "vue";

export const errors = Vue.observable({ count: 0 });

Component1.vue

import { errors } from 'path-of-errors.js'

export default {
  computed: {
    errors () {
      get () { return errors.count },
      set (val) { errors.count = val }
    }
  }
}

In Component1 the errors.count is reactive. So if as a template you have:

<template>
  <div>
    Errors: {{ errors }} 
    <button @click="errors++">Increase</button>
  </div>
</template>

While you click the Increase button, you will see the errors increasing.


As you might expect, when you import the errors.js in another component, then both components can participate on manipulating the errors.count.


Note: Even though you might use the Vue.observable API for simple data sharing you should be aware that this is a very powerful API. For example read Using Vue Observables as a State Store


App.vue:


<router-view pass_data='myData'/>

Sidekick.vue:


export default {
  name: "Sidekick",
  props: ["pass_data"],
  created() {
    alert("pass_data: "+this.pass_data)
  }
}