在 Vue 3.0 中使用 Element Plus(ElementUI 的 Vue 3 版本)给按钮添加跳转链接有以下几种常用方法
在 Vue 3.0 中使用 Element Plus(ElementUI 的 Vue 3 版本)给按钮添加跳转链接有以下几种常用方法:使用 router-link 包裹按钮
vue
Apply
<router-link to="/target-path">
<el-button type="primary">跳转按钮</el-button>
</router-link>
使用 @click 配合 router.push()
vue
Apply
<template>
<el-button type="primary" @click="handleClick">跳转按钮</el-button>
</template>
<script setup>
import { useRouter } from 'vue-router'
const router = useRouter()
const handleClick = () => {
// 方式1:字符串路径
router.push('/target-path')
// 方式2:对象形式
router.push({
path: '/target-path',
query: { id: 123 } // 可以带参数
})
// 方式3:命名路由
router.push({
name: 'RouteName',
params: { id: 123 }
})
}
</script>
使用 window.location 直接跳转
vue
Apply
<template>
<el-button type="primary" @click="handleClick">跳转按钮</el-button>
</template>
<script setup>
const handleClick = () => {
// 跳转到外部链接
window.location.href = 'https://example.com'
// 或者新窗口打开
window.open('https://example.com', '_blank')
}
</script>
使用 a 标签包裹
vue
Apply
<a href="https://example.com" target="_blank">
<el-button type="primary">跳转按钮</el-button>
</a>
使用 link 属性(如果需要按钮样式为链接形式)
vue
Apply
<el-link type="primary" href="https://example.com" target="_blank">
链接按钮
</el-link>
各种方法的使用场景:router-link
适用于内部路由跳转
SEO 友好
可以保持单页应用的特性
router.push()
适用于需要在跳转前执行一些逻辑的场景
可以携带更复杂的参数
可以更灵活地控制跳转行为
window.location
适用于跳转到外部链接
会刷新页面
可以跳转到任何 URL
a 标签
最简单的方式
适合简单的外部链接跳转
SEO 友好
el-link
当你想要链接样式而不是按钮样式时使用
Element Plus 内置的链接组件
提供了更多的样式选项
注意事项:内部路由跳转优先使用 vue-router 的方式(router-link 或 router.push)
外部链接跳转可以使用 a 标签或 window.location
需要在跳转前进行逻辑处理时,使用 @click 事件处理器
记得在使用 router.push 之前先引入 useRouter
这些方法可以根据具体需求灵活选择使用。例如,如果是简单的页面内部跳转,用 router-link 就足够了;如果需要在跳转前做一些验证或数据处理,则可以使用 @click 配合 router.push()。