vue46 —— vue-router:router-link 补充

本文深入探讨了vue-router的router-link组件,包括如何通过`tag`属性改变默认渲染标签,利用`replace`属性避免浏览器历史记录,管理活跃状态的`active-name`和`linkActiveClass`,以及如何进行路由的代码级跳转。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

router-link默认最终渲染为a标签

改变最终渲染: tag属性

App.vue:

<router-link to='/home' tag='button'>首页</router-link>

tag=’标签名‘,最终渲染为设置的标签

改pushState为replace: replace属性

使前进后退不可使用

<router-link to='/home' tag='button' replace>首页</router-link>
 <router-link to='/about' replace>关于</router-link>

活跃状态自动添加的类名: active-name

在这里插入图片描述
处于活跃状态的router-link,会自动添上两个类名,
第一个是嵌套路由相关,暂且不说;(与active-class类似,只是在精准匹配下才会出现的class)
可通过第二个类名,设置活跃状态样式

App.vue:
改变默认的类名为自定义的类名:

<router-link to='/home' tag='button' replace active-class='active'>首页</router-link>
<router-link to='/about' replace active-class='active'>关于</router-link>

active-class='active'
在这里插入图片描述

linkActiveClass

当要改变类名的项很多时,可以在index.js中统一设置

const router = new VueRouter({
  // 配置路径和组件之间的映射关系
  routes,
  mode: 'history',
  linkActiveClass: 'active'  // 活跃状态类名
})

路由代码跳转

不使用router-link标签

App.vue:

...
    <button @click="toHome">首页</button>
    <button @click="toAbout">关于</button>
    <router-view></router-view>
...
<script>
export default {
  name: 'App',
  methods:{
    toHome(){
     // this.$router.push('/home')
        this.$router.replace('/hmoe')
    },
    toAbout(){
     // this.$router.push('/about')
        this.$router.replace('/about') 
    }
  }
}
</script>

这里连续点击同一个按钮会报错
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值