首页 > 解决方案 > vuejs - 用于不同 url 的缓存数据

问题描述

我已经建立了一个配置文件 vue 页面,但我意识到当我更改 URL 参数时,它不会加载新用户,而是显示第一个用户。我加载created可能是原因的数据。我如何告诉页面它有不同的参数并且它应该重新加载?

路由器.js

export default new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/profile/:id',
      name: 'user-profile',
      component: () => import('./views/Profile.vue'),
      props: true,
    },

个人资料.vue

async created() {
  const response = await this.$store.dispatch('GET_USER_PROFILE_BY_ID', { id: this.id });
  this.userProfile = response.data.data;

网址:

标签: vue.js

解决方案


created 钩子仅在组件实际创建时执行。更改 url 以加载相同的路由,但使用不同的 ID 是 routeUpdate 代替。

请记住,参数或查询更改不会触发进入/离开导航守卫。您可以观察 $route 对象以对这些更改做出反应,也可以使用组件内的 beforeRouteUpdate 保护。
https://router.vuejs.org/guide/advanced/navigation-guards.html

抽象出您在创建的钩子中拥有的 fetch & set。然后,在 created() 和 beforeRouteUpdate() 中调用它。

{
methods: {
    async getProfile(id) {
        const response = await this.$store.dispatch('GET_USER_PROFILE_BY_ID', { id});
        this.userProfile = response.data.data;
    }
    created() { this.getProfile(this.id); },
    beforeRouteUpdate(to, from, next) { 
        const { params: {id} } = to;
        this.getProfile(id); 
        next(); 
    }
}

推荐阅读