[英]Synchronize variable between router in 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
因为它紧密耦合了各个组件。
我不会详细介绍执行此操作的更好方法,因为有很多SO问题都涉及此主题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.