javascript - Vue-路由器数据获取: Fetch Data before 'beforeRouteUpdate' loads component

标签 javascript vuejs2 axios vuex vue-router

我是 vue-router 导航防护的新手,所以我最近意识到我需要使用 beforeRouteUpdate 防护来重用组件,例如:从 /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 已经加载下一个组件。

最佳答案

首先,您的操作应该执行任何状态突变,例如将 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。例如,假设你的 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 中建议的方法

关于javascript - Vue-路由器数据获取: Fetch Data before 'beforeRouteUpdate' loads component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52069910/

相关文章:

javascript - 多次触发 jQuery 动画 API

javascript - 发出 ajax 请求时出现 403 禁止错误

javascript - 未使用 VueJS mixins 定义属性

javascript - 本例中如何使用动态参数(ID)来调用 axios api

javascript - 使用 axios POST 请求更新 JSON

javascript - 分析javascript生成的网页

javascript - 如何为 a+ b 编写 js 重定向规则以始终将 a 放在 b 之前,即使在 b+a 场景中也是如此?

javascript - 语法错误 : let is disallowed as a lexically bound name

javascript - 如何在函数式 Vuejs 组件中发出事件

javascript - 在 for 循环中使用 axios.get