简体   繁体   English

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

[英]Synchronize variable between router in vue.js

I'd like to change value of a variable in a router-view by changing other variable in different routre-view synchronously. 我想通过在其他routre-view同步更改其他变量来更改router-view中的变量值。 I wrote code like below to change variable isFoo in header and catch it in side bar, but it fails. 我写了如下代码来更改标头中的变量isFoo并将其捕获到边栏中,但失败。

App.vue: 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>

and Sidebar.vue: 和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: 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>

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. 您的代码不起作用,因为您已在组件之间复制了isFoo ,而不是仅引用该数据的单个真实来源。 Also you should specify reactive data in the data property of each component, not directly within the $options of the component. 另外,您应该在每个组件的data属性中指定反应性数据,而不是直接在组件的$options中指定。

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. 您确实不应该访问this.$parent因为它紧密耦合了各个组件。

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. 我不会详细介绍执行此操作的更好方法,因为有很多SO问题都涉及此主题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM