在 Vue 中有多种方式可以实现点击跳转页面,以下几种实用技巧亲测有效哦~
目录
四、this.$router 或 router 实例进行页面跳转路由
五、window.location 或 window.open() 进行原生页面跳转
一、<router-link> 组件
<router-link> 是 Vue Router 提供的官方组件,用于在 Vue 应用程序中创建导航链接,激活时可以自动添加CSS类,处理活性状态,并且支持 <a> 标签的全部特性。
<router-link to="/login"></router-link>
如果准备跳转的路由携带参数,to 需要加上冒号
<div v-for="(item, index) in questions" :key="index">
<router-link :to="`/question/${item.id}`"></router-link>
</div>
二、<a> 标签
传统的 HTML <a> 标签也可以用来实现页面跳转路由。
<a href="/login"></a>
三、@click 事件监听器
在任何元素上使用 @click 事件监听器,搭配使用 $router.push() 或 $router.replace() 这两个方法可以手动地通过添加或替换当前历史记录条目来跳转到不同的路由,还可以在事件处理函数中调用路由跳转方法。
<button @click="$router.push('/login')"></button>
四、this.$router 或 router 实例进行页面跳转路由
1、如果你需要在某个事件(如按钮点击)中进行页面跳转,可以使用 Vue Router 的实例方法 this.$router.push() 或 this.$router.replace() 方法。
<template>
<div>
<button @click="toTargetPage">点击跳转</button>
</div>
</template>
<script>
export default {
methods: {
toTargetPage() {
// 使用 push 方法进行跳转,会在浏览历史中添加记录
this.$router.push('/targetPage');
// 或者使用 replace 方法,不会添加新的历史记录,替换当前的历史记录
// this.$router.replace('/targetPage');
}
}
}
</script>
2、如果你在组合式 API(Composition API)中,可以使用 useRouter 钩子来访问 router 实例并进行导航,同样有 router.push() 和 router.replace() 两种方法。
<script setup>
import { useRouter } from "vue-router";
const router = useRouter();
const toTargetPage = () => {
// 直接跳转
// router.push('/targetPage')
// router.replace('/targetPage')
// 传递参数的方式,有 query 和 params 两种
router.push({
path: "/targetPage",
query: {
uuid: item.id,
projectName: item.projectName
}
})
}
</script>
五、window.location 或 window.open() 进行原生页面跳转
1、在不使用 Vue Router 的情况下,可以使用原生 JavaScript 的 window.location 对象进行页面跳转。
const toLogin = () => {
window.location.href = '/login'
}
2、widow.open() 方法加上 '_blank' 可以实现在新窗口打开页面。
const toQuestionPage = (question: Question) => {
window.open(`/question/${question.id}`, '_blank');
};
大家如果还有其他想补充的,欢迎在评论区留言哦~