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

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

问题描述:

我想通过同步更改不同routre-view中的其他变量来更改router-view中某个变量的值。我编写了如下代码来更改头文件中的变量isFoo并在侧栏中捕获它,但失败。vue.js中路由器之间的同步变量

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,因为它紧密耦合组件。

我不打算详细讨论这样做的更好方法,因为有lots of SO questions涵盖此主题。