[Vuejs]-Synchronize variable between router in vue.js

0👍

Your question is essentially about how to share state across multiple components of your app, and is quite general.

Your code does not work because you have copied isFoo across your components instead of just referencing a single source of truth for that data. Also you should specify reactive data in the data property of each component, not directly within the $options of the component.

I’ve fixed your code to make it work:

const Header = {
  template: '<button @click="$parent.isFoo = true">Click Me</button>'
}

const Sidebar = {
  template: '<div>Sidebar: {{ $parent.isFoo }}</div>'
}

const router = new VueRouter({
  routes: [
    {
      path: '/',
      components: {
        header: Header,
        sidebar: Sidebar
      }
    }
  ]
})

new Vue({
  router,
  el: '#app',
  data: {
    isFoo: false
  }
})
<script src="https://rawgit.com/vuejs/vue/dev/dist/vue.js"></script>
<script src="https://rawgit.com/vuejs/vue-router/dev/dist/vue-router.js"></script>

<div id="app">
  <router-view name="header"></router-view>
  <router-view name="sidebar"></router-view>
</div>

However I do not recommend this approach. You really shouldn’t be accessing this.$parent because it tightly couples the components.

I’m not going to go into detail about better ways of doing this because there are lots of SO questions which cover this topic.

Leave a comment