在 vue.js 中返回上一页的方法是使用window.history.go(-1)。步骤如下:1. 导入 history 模块。2. 在组件中使用 window.history.go(-1) 方法返回上一页。

如何在 Vue.js 中返回上一页
在 Vue.js 应用中返回上一页的方法是使用 window.history.go(-1)。此方法通过 JavaScript 返回浏览器历史记录中的前一页。
具体步骤:
-
导入
history模块:立即学习“前端免费学习笔记(深入)”;
<code class="js">import { history } from 'vue-router'</code> -
在需要返回上一页的组件中,使用
window.history.go(-1):<code class="js">return window.history.go(-1)</code>
示例:
以下代码是一个使用 window.history.go(-1) 返回上一页的按钮:
<code class="html"><template>
<button @click="goBack">返回</button>
</template>
<script>
import { history } from 'vue-router'
export default {
methods: {
goBack() {
window.history.go(-1)
}
}
}
</script></code>注意:
-
window.history.go(-1)仅在浏览器中有效。 - 如果当前页面没有历史记录(例如,是从外部网站直接访问的),则此方法将不会起作用。
- 也可以使用
$router.go(-1)返回上一页,但它与window.history.go(-1)效果相同。










