vue.js-如何在更改路由时管理vuex状态

时间:2019-06-29 15:56:13

标签: vue.js vuejs2 vuex vue-router

我有这样的路线:

  • /forum/abc/user/23/{posts, profile,...}
  • /forum/cde/user/28/{posts,profile,...}

在我的Vuex商店中,我想拥有当前的ForumUser对象,以便Profile.vue之类的组件可以访问它们。

state: {
  forum: null,
  user: null,
}

当路由器进入/forum/abc/user/23时,应加载forumuser。当用户导航到/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>

在我的路线中,我嵌套了ForumUser,所以它们总是包含在内,但它们不呈现任何内容。他们只是负责更改路线并触发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商店内实现?

0 个答案:

没有答案