按钮 UButton
按钮是界面里最高频的元素。Nuxt UI 的 UButton 把颜色、样式、图标、加载态都封装好了,写几个属性就能得到统一的视觉效果。
本篇基于 Nuxt UI 入门与安装 接好的环境,专注讲 UButton 的常用玩法。
基本用法
组件自动导入,直接在模板里写 <UButton> 就行。
<template>
<UButton>点我</UButton>
</template>
不写任何属性时,按钮是主题色(primary)的实心样式,这是 Nuxt UI 的默认设定。
颜色 color
color 控制按钮的主色,内置一组语义色。
<template>
<UButton color="primary">主要</UButton>
<UButton color="secondary">次要</UButton>
<UButton color="success">成功</UButton>
<UButton color="info">信息</UButton>
<UButton color="warning">警告</UButton>
<UButton color="error">错误</UButton>
<UButton color="neutral">中性</UButton>
</template>
primary 是主题色(可在 主题与暗色模式 里改),其余色名是固定语义色,适合表达不同操作的含义,比如删除用 error、确认用 success。
变体 variant
variant 控制按钮的「填充方式」,和 color 搭配出不同轻重。
<template>
<UButton variant="solid">实心</UButton>
<UButton variant="outline">描边</UButton>
<UButton variant="soft">柔和</UButton>
<UButton variant="subtle">淡底</UButton>
<UButton variant="ghost">幽灵</UButton>
<UButton variant="link">链接</UButton>
</template>
实际项目里,主操作常用 solid,次要操作常用 soft 或 ghost,这样界面有主次之分。
尺寸 size 与形状
size 有 xs、sm、md、lg、xl,默认 md。
<template>
<UButton size="xs">超小</UButton>
<UButton size="md">默认</UButton>
<UButton size="xl">超大</UButton>
</template>
square 让按钮变成正方形(只留图标时常用),block 让按钮占满整行宽度。
<template>
<UButton square icon="i-lucide-settings" />
<UButton block>整行按钮</UButton>
</template>
图标 icon
按钮里加图标用 icon(leading 位置)或 trailing-icon(右侧位置)。Nuxt UI 的图标名是 i-<集合>-<名字>,默认用 lucide 图标集,比如 i-lucide-plus。图标的整体用法见 图标 Icon。
<template>
<UButton icon="i-lucide-plus">新建</UButton>
<UButton icon="i-lucide-trash" trailing-icon="i-lucide-arrow-right" color="error">
删除
</UButton>
</template>
也可以放头像,用 avatar 属性传一个头像配置对象。
加载态 loading
提交按钮最常用「点了之后转圈」的效果。loading 手动控制,loading-auto 更省事,它会根据你的 @click 处理函数返回的 Promise 自动决定转圈时机。
<template>
<UButton :loading="pending" @click="save">手动加载</UButton>
<UButton loading-auto @click="saveAuto">自动加载</UButton>
</template>
<script setup>
const pending = ref(false)
async function save() {
pending.value = true
await new Promise(r => setTimeout(r, 1000))
pending.value = false
}
// loading-auto 会等这个 Promise 结束才停止转圈
function saveAuto() {
return new Promise(r => setTimeout(r, 1000))
}
</script>
loading-auto 适合「点一下发请求,请求期间禁用按钮」这种标准场景,不用自己维护 pending 变量。
作为链接
按钮经常要跳转页面,直接给 to 属性即可,它会渲染成 <NuxtLink>。
<template>
<UButton to="/about" icon="i-lucide-arrow-right">去关于页</UButton>
<UButton to="https://nuxt.com" target="_blank" variant="link">外链</UButton>
</template>
完整示例
把上面属性组合起来,做一个带图标的加载按钮。
<template>
<UButton
color="primary"
variant="solid"
size="md"
icon="i-lucide-save"
loading-auto
@click="onSave"
>
保存
</UButton>
</template>
<script setup>
function onSave() {
return new Promise(r => setTimeout(r, 800))
}
</script>
常见问题
| 问题 | 解决方法 |
|---|---|
| 图标不显示 | 确认图标名拼写正确(如 i-lucide-plus),并接入了图标(见 图标 Icon) |
| 按钮没有主题色 | 检查 app.config.ts 里 ui.colors.primary 是否设置,详见 主题与暗色模式 |
loading-auto 不生效 |
确认 @click 处理函数返回了 Promise |