vue点击跳转页面技巧大揭秘,多种高效方式任你选择!

 在 Vue 中有多种方式可以实现点击跳转页面,以下几种实用技巧亲测有效哦~

目录

一、<router-link> 组件

二、<a>标签

三、@click 事件监听器

四、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.locationwindow.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');
};

 

大家如果还有其他想补充的,欢迎在评论区留言哦~

  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_jsdhwdmaX_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值