首页 文章

Vue-Router数据获取:在'beforeRouteUpdate'加载组件之前获取数据

提问于
浏览
0

我是vue-router导航卫士的新手,所以我最近意识到我需要使用 beforeRouteUpdate guard来重用组件,例如:从 /foo/1/foo/2

然而,在来到 /foo/1 时,我通过axios调用从数据库中提取数据,在进入 /foo/2 之前,我需要通过axios调用再次提取新数据 .

这是我遇到的问题,导航防护 beforeRouteUpdate 在我从axios调用加载数据之前加载组件 /foo/2 因此我在一些变量中得到null .

如何使 beforeRouteUpdate 等待加载下一个组件,以便从axios调用加载我的所有数据?

至于我的代码,它看起来像这样:

beforeRouteUpdate (to, from, next) {
    Vue.set(this.$store.state.user, 'get_user', null)
    this.$store.dispatch(OTHER_PROFILE_GET, to.params.id).then(resp => {
      console.log(resp);
      if(this.$store.getters.is_user_loaded) {

        next()

      } else {

        this.$store.watch((state, getters) => getters.is_user_loaded, () => 
        {
          if(this.$store.getters.is_user_loaded) {
            console.log(this.$store.state.user.get_user);
            console.log('comes here');
            next()
          }
        })
      }
    })
},

为了进一步解释我的代码,我在我的组件中调用了这个方法,所以当我从 /user/1 转到 /user/2 时,我调度了一个Vuex动作,它发出了一个axios调用来获取新的配置文件细节,但在axios调用完成之前并加载数据在Vuex状态下, beforeRouteUpdate 已经加载了下一个组件 .

1 回答

  • 0

    首先,您的操作应执行任何状态突变,例如将 user.get_user 设置为 null . 我添加了一块 Watch ;您的操作应该只在完成时解决 . 例如

    actions: {
      [OTHER_PROFILE_GET] ({ commit }, id) {
        commit('clearUserGetUser') // sets state.user.get_user to null or something
        return axios.get(`/some/other/profile/${encodeURIComponent(id)}`).then(res => {
          commit('setSomeStateData', res.data) // mutate whatever needs to be set
        })
      }
    }
    

    然后你的护卫队应该有类似的东西

    beforeRouteUpdate (to, from, next) {
      this.$store.dispatch(OTHER_PROFILE_GET, to.params.id).then(next)
    }
    

    为了防止错误尝试呈现 null 数据,请使用您的getter . 例如,说你的吸气剂是

    getters: {
      is_user_loaded (state) {
        return !!state.user.get_user
      }
    }
    

    在您的组件中,您可以将其映射到计算属性...

    computed: {
      isUserLoaded () {
        return this.$store.getters.is_user_loaded // or use the mapGetters helper
      },
      user () {
        return this.$store.state.user.get_user // or use the mapState helper
      }
    }
    

    然后在您的模板中,使用此逻辑有条件地呈现一些数据

    <div v-if="isUserLoaded">
      Hello {{user}}
    </div>
    <div v-else>
      Loading...
    </div>
    

    这是vue-router guide for beforeRouteUpdate中建议的方法

相关问题