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,
},

Profile.vue

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

网址:

  • http://localhost:8080/profile/1dvklq9cnz
  • http://localhost:8080/profile/1e0tcb2kn2

创建的钩子仅在实际创建组件时执行。 更改 URL 以加载相同的路由,但具有不同的 ID 是路由更新。

请记住,参数或查询更改不会触发进入/离开导航守卫。您可以监视 $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(); 
}
}

最新更新