的replace属性:
- 作用:控制路由跳转时操作历史记录的模式,如果加上了replace属性则跳转后会清除之前所有历史记录使浏览器不能后退
- 使用方法(模板):
<router-link replace to="/reg">点击replace</router-link>
除这种用法外,也可以使用编程式路由导航router.replace
<template>
<h1>小满最骚</h1>
<button @click="replace">replace</button>
<router-view></router-view>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const replace = () => {
router.replace('/reg')
}
</script>
<style scoped></style>
需要注意的是,router.replace中传入对象并指定name属性的方法已被废弃,若要使用配置对象请用path属性
<template>
<h1>小满最骚</h1>
<button @click="replace">replace</button>
<router-view></router-view>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const replace = () => {
router.replace({
path:'/reg',
})
}
</script>
<style scoped></style>
go与back
作用:横跨历史,采用一个整数作为参数,表示在历史记录中前进或后退多少步
<template>
<h1>小满最骚</h1>
<button @click="next">next</button>
<br />
<button @click="back">back</button>
<router-view></router-view>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const next = () => {
// 正数表示前进,负数表示后退
router.go(1)
}
const back = () => {
router.back()
}
</script>
完整示例:
<template>
<h1>小满最骚</h1>
<router-link replace to="/reg">点击replace</router-link>
<button @click="toPage('Login')">Login</button>
<br />
<button @click="toPage('Reg')">Reg</button>
<br />
<button @click="next">next</button>
<br />
<button @click="back">back</button>
<br />
<button @click="replace">replace</button>
<router-view></router-view>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const toPage = (name: string) => {
router.push({
name,
})
}
const replace = () => {
router.replace({
path:'/reg',
})
}
const next = () => {
router.go(1)
}
const back = () => {
router.back()
}
</script>
<style scoped></style>