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



我想通过同步更改其他routre-view中的其他变量来更改router-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>

您的问题本质上是关于如何在应用程序的多个组件上共享状态,并且是一般性的。

您的代码不起作用,因为您已经在组件上复制了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,因为它紧密地耦合了组件。

我不会详细介绍这样做的更好的方法,因为有很多涵盖此主题的问题。

最新更新