2017-12-18 98 views
0

我想通過同步更改不同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> 

回答

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涵蓋此主題。