我有这样的路线:
/forum/abc/user/23/{posts, profile,...}
/forum/cde/user/28/{posts,profile,...}
在我的Vuex商店中,我想拥有当前的Forum
和User
对象,以便Profile.vue
之类的组件可以访问它们。
state: {
forum: null,
user: null,
}
当路由器进入/forum/abc/user/23
时,应加载forum
和user
。当用户导航到/forum/abc/user/23/posts
时,不需要重新加载数据,但是当用户切换到/forum/def/user/28/posts
时,需要更新状态。
此刻,我用嵌套路线解决了它。我有一个Forum.vue
组件和一个User.vue
组件,它们相似,看起来像这样:
论坛。
<template>
<!-- "Key" to signal Vue to rerender the component on param change -->
<router-view :key="this.$route.path"></router-view>
</template>
<script>
import store from "@/store/store.js";
export default {
beforeRouteEnter(to, from, next) {
store.dispatch("fetchForum");
},
beforeRouteUpdate(to, from, next) {
store.dispatch("fetchForum");
},
}
</script>
在我的路线中,我嵌套了Forum
和User
,所以它们总是包含在内,但它们不呈现任何内容。他们只是负责更改路线并触发Vuex商店更新。
export default {
path: "/forum/:forum([a-z]+)/",
components: {
default: Forum,
navigation: Navigation,
},
props: true,
children: [
{
path: "",
name: "ForumHome",
component: ForumHome,
},
{
path: "/user/:user([0-9]+)/",
name: "User",
component: User,
props: true,
children: [
{
path: "",
name: "UserHome",
component: UserHome
}
]
},
]
}
定义一个侦听路由器事件以更新状态的视图组件对我来说很奇怪。
这是在Vuex / Vue / VueRouter中解决此问题的正确方法吗?还是应该以某种方式在Vuex商店内实现?