vue实现后退按钮
实现后退按钮的方法
在Vue中实现后退按钮功能,可以通过以下几种方式:

使用window.history API

methods: {
goBack() {
window.history.back();
}
}
使用Vue Router的router.go()方法
methods: {
goBack() {
this.$router.go(-1);
}
}
完整组件示例
<template>
<button @click="goBack">返回</button>
</template>
<script>
export default {
methods: {
goBack() {
if (window.history.length > 1) {
this.$router.go(-1);
} else {
this.$router.push('/');
}
}
}
}
</script>
注意事项
- 检查历史记录长度可以避免在没有历史记录时出现问题
- 在Vue单页应用中,推荐使用Vue Router的方法
- 可以添加备用路由以防没有历史记录可返回
进阶实现
<template>
<button @click="handleBack">
<slot>返回</slot>
</button>
</template>
<script>
export default {
props: {
fallbackRoute: {
type: [String, Object],
default: '/'
}
},
methods: {
handleBack() {
if (window.history.length > 1) {
this.$router.go(-1);
} else {
this.$router.push(this.fallbackRoute);
}
}
}
}
</script>
这种方式创建了可复用的后退按钮组件,支持自定义回退失败时的备用路由和按钮内容。






