在vue.js中同步路由器之间的变量

时间:2017-12-18 02:55:23

标签: javascript vue.js

我想通过同步更改不同router-view中的其他变量来更改routre-view中变量的值。我编写了如下代码来更改标题中的变量isFoo并在侧栏中捕获它,但它失败了。

App.vue:

<template>
  <v-app id="app">
    <router-view name="sidebar"></router-view>
    <router-view name="header"></router-view>
    <router-view name="main"></router-view>
    <router-view name="footer"></router-view>
  </v-app>
</template>
<script>
export default {
  name: 'app',
  isFoo: false
}
</script>

和Sidebar.vue:

<template>
  <div id="sidebar" :isOpen="isFoo"></div>
</template>
<script>
  export default {
    name: 'sidebar',
    data () {
      return {isFoo: this.$parent.$options.isFoo}
    }
  }
</script>

Header.vue:

<template>
  <button v-on:click="foo()">Button</button>
</template>
<script>
export default {
  name: 'header',
  methods: {
    foo: () => {
      this.$parent.$options.isFoo = !this.$parent.$options.isFoo
    }
  }
}
</script>

1 个答案:

答案 0 :(得分:0)

您的问题主要是关于如何在应用的多个组件之间共享状态,这是非常笼统的。

您的代码无效,因为您已在组件中复制了isFoo,而不仅仅是引用该数据的单一事实来源。您还应该在每个组件的data属性中指定反应数据,而不是直接在组件的$options内。

我已修复您的代码以使其正常工作:

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>

然而我不推荐这种做法。你真的不应该访问this.$parent,因为它紧密地耦合了组件。

我不打算详细介绍更好的方法,因为lots of SO questions涵盖了这个主题。