gpt4 book ai didi

vue.js - 为什么浏览器会在路由/url 更改时显示缓存的 Vue.js View ?

转载 作者:行者123 更新时间:2023-12-05 01:13:01 25 4
gpt4 key购买 nike

我有一个带有 <router-link> 的主页 View 的标签。这是一个简单的主/详细关系,其中 Homepage是产品目录和 Product详细信息页面/ View 显示每个项目的信息。

当我第一次启动网站并单击 Homepage 上的一个项目时查看(例如 URL:http://localhost:8080/100-sql-server-2019-licence),Product View 已加载,产品详细信息加载正常。

如果我在浏览器中按下返回按钮返回到 Homepage然后点击不同的Product (例如 URL:http://localhost:8080/101-oracle-12c-licence ),浏览器地址栏中的 URL 发生了变化,但我得到了以前产品的信息。它闪电般的快速,并且没有进行新的网络调用,这意味着它只显示了以前产品的缓存页面。如果我在该页面上点击刷新按钮,则会进行网络调用并显示正确的产品信息。

我在网上进行了搜索,但在搜索结果中找不到描述的这个问题。谁能指出我在路线更改时如何导致路线刷新/重新渲染的正确方向?

最佳答案

发生了什么

vue-router默认情况下将缓存您的组件。
因此,当您导航到第二个产品(它可能呈现与第一个产品相同的组件)时,出于性能原因,该组件将不会再次实例化。

来自 vue-router documentation :

For example, for a route with dynamic params /foo/:id, when we navigate between /foo/1 and /foo/2, the same Foo component instance will be reused.

简单(但肮脏)的修复

解决此问题的简单但不成熟且不推荐的方法是提供您的 <router-view />关键属性,例如:

<router-view :key="$route.fullPath" />

这将强制 vue-router每次 url 更改时重新实例化 View 组件。
但是,您将失去通常从缓存中获得的所有性能优势。

彻底修复:正确处理路由更改

解决此问题的简洁方法是对组件中的路由更改使用react(主要归结为将 ajax 调用从 mounted 转移到 $route 观察者),例如:

<script>
export default {
data() {
return {
productDetails: null,
loading: false
};
},
watch: {
'$route': {
// with immediate handler gets called on first mount aswell
immediate: true,
// handler will be called every time the route changes.
// reset your local component state and fetch the new data you need here.
async handler(route) {
this.loading = true;
this.productDetails = null;
try {
// example for fetching your product data
const res = await fetch("http://give.me.product.data/" + encodeURIComponent(route.params.id));
this.productDetails = await res.json();
} finally {
this.loading = false;
}
}
}
}
};
</script>

备选方案:导航守卫

或者你也可以使用 vue-router s In-Component Navigation Guards对路线变化使用react:

<script>
export default {
async beforeRouteUpdate (to, from, next) {
// TODO: The route has changed.
// The old route is in `from`, the new route in `to`.
this.productData = await getProductDataFromSomewhere();

// route will not change before you haven't called `next()`
next();
}
};
</script>
  • 导航守卫的缺点是你只能直接在路由渲染的组件中使用它们。
    因此,您不能在层次结构中更深层的组件中使用导航守卫。
  • 好处是在您调用 next() 之前浏览器不会查看您的网站,这样您就有时间在显示路线之前加载必要的数据。

一些有用的资源

关于vue.js - 为什么浏览器会在路由/url 更改时显示缓存的 Vue.js View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61062749/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com