惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Threat Research - Cisco Blogs
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
月光博客
月光博客
V
Vulnerabilities – Threatpost
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
S
Secure Thoughts
Microsoft Azure Blog
Microsoft Azure Blog
Blog — PlanetScale
Blog — PlanetScale
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
T
Tailwind CSS Blog
S
SegmentFault 最新的问题
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
云风的 BLOG
云风的 BLOG
The Last Watchdog
The Last Watchdog
L
LINUX DO - 热门话题
酷 壳 – CoolShell
酷 壳 – CoolShell
WordPress大学
WordPress大学
AWS News Blog
AWS News Blog
美团技术团队
G
Google Developers Blog
宝玉的分享
宝玉的分享
www.infosecurity-magazine.com
www.infosecurity-magazine.com
C
CXSECURITY Database RSS Feed - CXSecurity.com
Recent Commits to openclaw:main
Recent Commits to openclaw:main
I
InfoQ
小众软件
小众软件
Google DeepMind News
Google DeepMind News
P
Privacy & Cybersecurity Law Blog
Stack Overflow Blog
Stack Overflow Blog
Webroot Blog
Webroot Blog
D
DataBreaches.Net
IT之家
IT之家
PCI Perspectives
PCI Perspectives
人人都是产品经理
人人都是产品经理
Hacker News: Ask HN
Hacker News: Ask HN
L
LangChain Blog
SecWiki News
SecWiki News
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
Cisco Blogs
T
Threatpost
P
Proofpoint News Feed
Y
Y Combinator Blog
Cloudbric
Cloudbric
T
Tor Project blog
量子位
博客园_首页
B
Blog
Hugging Face - Blog
Hugging Face - Blog
GbyAI
GbyAI
D
Darknet – Hacking Tools, Hacker News & Cyber Security

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Vue 3 Simple Component Development: API Design from the Button Component
yuelinghuashu · 2026-06-12 · via DEV Community

Minimalism is not crudeness, restraint is not deficiency — drawing inspiration from Nuxt UI v4, how to design a well-crafted component API

This article covers: Props definition, variant system (variant + color), size trade-offs (why remove xs/xl), slot design (label prop vs default slot), loading state handling (including CLS prevention), accessibility attributes, and a comparison table with mainstream UI libraries.


I. Background and Reference

In previous articles, we discussed the concept of design tokens over atomic CSS, and the architecture of CSS-first + thin component wrappers. But one question remains unanswered: How should a single component's API be designed?

Early in the design process, I deeply referenced Nuxt UI v4's approach. Nuxt UI v4 consolidates complex styles and interactions into a few core dimensions — variant/color/size. This is exactly what I wanted: encapsulate complexity inside the component, exposing only the most streamlined API to the outside.

This article uses the Button component as an example to walk through my design trade-offs and thought process step by step.

II. Starting from Requirements: What Does a Button Need?

A button component's most basic functionality:

  • Display text
  • Trigger events on click
  • Disabled state
  • Different styles (primary, secondary, danger, etc.)

But is that enough? Let's look at real usage scenarios:

<!-- Button with icon -->
<Button>
  <template #icon>🔍</template>
  Search
</Button>

<!-- Loading state -->
<Button loading>Submitting</Button>

<!-- Block button (full width) -->
<Button block>Full Width Button</Button>

<!-- Different sizes -->
<Button size="sm">Small</Button>

After analysis, the Button component needs to support:

Requirement Implementation
Text content Default slot or label prop
Click event click event
Disabled state disabled prop
Loading state loading prop
Different styles variant + color
Different sizes size prop
Block width block prop
Icon #icon slot

III. Props Design: Types, Defaults, Priority

3.1 Base Props

interface Props {
  label?: string;      // Button text
  disabled?: boolean;  // Disabled state
  loading?: boolean;   // Loading state
  block?: boolean;     // Block level
}

Default value design:

const props = withDefaults(defineProps<Props>(), {
  label: "",
  disabled: false,
  loading: false,
  block: false,
});

3.2 Variant System: variant + color

Common button types include: primary, secondary, outline, ghost. Inspired by Nuxt UI v4's variant + color design, I chose to completely decouple "visual mode" from "semantic color".

type Variant = "filled" | "outline";
type Color = "primary" | "success" | "warning" | "error";

Why keep only filled and outline, removing ghost?

Variant Usage Frequency Keep?
filled 🔥🔥🔥🔥🔥 Extremely high ✅ Keep
outline 🔥🔥🔥🔥 High ✅ Keep
ghost 🔥 Low ❌ Removed (can be replaced by outline)

Similarly, keep only 4 colors:

Color Usage Frequency Keep?
primary 🔥🔥🔥🔥🔥 Extremely high ✅ Keep
success 🔥🔥🔥 Medium ✅ Keep
warning 🔥 Low ✅ Keep
error 🔥🔥 Medium ✅ Keep
neutral 🔥 Low ❌ Removed (can be replaced by outline)

3.3 Size Design

type Size = "sm" | "md" | "lg";

Compared with Nuxt UI v4's five sizes (xs, sm, md, lg, xl), I made a simplification. I removed xs and xl because the smallest use cases can be covered by Badge or other non-button components, and I rarely encounter extra-large buttons in a personal blog context.

Default size selection: Mainstream UI libraries (Naive UI, PrimeVue, etc.) have default button heights around 32-34px, which corresponds to our sm, so the default size is sm.

const props = withDefaults(defineProps<Props>(), {
  size: "sm", // default small
});

3.4 Icon Design: Only Use Slots

To keep things minimalist, the Button component does not provide an icon prop, only the #icon slot. When users need an icon, they simply put content in the slot:

<Button>
  <template #icon>🔍</template>
  Search
</Button>

Although this requires a few more characters, it avoids confusion between prop and slot priority, and better follows the single responsibility principle. Also, the slot can accept any content (strings, emojis, icon components), with complete flexibility.

Design consideration: Nuxt UI v4 provides an icon prop and multiple icon-related attributes (leading-icon/trailing-icon). But in a personal blog context, the vast majority of icon buttons are simply "icon + text", and using a slot is sufficient for all use cases, reducing learning and maintenance costs.

IV. Slot Design: Default Slot vs label Prop

To support both quick writing and custom content, provide both label prop and default slot:

<span class="mg-button-label">
  <slot>{{ label }}</slot>
</span>

  • If default slot content is provided, display it
  • Otherwise, display the label prop

Both usage styles are supported:

<!-- Using label prop -->
<Button label="Submit" />

<!-- Using default slot -->
<Button>Submit</Button>

V. State Handling

5.1 Disabled State

Both disabled and loading disable the button:

const isDisabled = computed(() => props.disabled || props.loading);

<button :disabled="isDisabled">

5.2 Loading State

Show a spinning animation when loading, hide icon and text:

<template v-if="loading">
  <span class="mg-button-loading-icon" />
</template>
<template v-else>
  <span v-if="hasIconSlot" class="mg-button-icon">
    <slot name="icon" />
  </span>
  <span v-if="hasLabel" class="mg-button-label">
    <slot>{{ label }}</slot>
  </span>
</template>

Pure CSS loading animation:

.mg-button-loading-icon {
  width: 1rem;
  height: 1rem;
  border: 2px solid currentColor;
  border-top-color: transparent;
  border-radius: 50%;
  animation: mg-button-spin 0.6s linear infinite;
}
@keyframes mg-button-spin {
  to {
    transform: rotate(360deg);
  }
}

VI. CSS Styling

6.1 Base Styles

Buttons use inline-flex layout, content centered both horizontally and vertically, with straight corners (--ui-radius-none), padding and font size using design tokens.

.mg-button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: var(--ui-spacing-sm);
  font-weight: 500;
  transition: all var(--ui-motion-duration-neural) ease;
  cursor: pointer;
  border-radius: var(--ui-radius-none);
  border: none;
  background: transparent;
  white-space: nowrap;
  padding: var(--ui-spacing-sm) var(--ui-spacing-md);
  font-size: var(--ui-typography-size-body);
}

6.2 Size Variants

Size Padding Font Size
sm sm / md --ui-typography-size-code (13px)
md md / lg --ui-typography-size-body (15px)
lg lg / xl 1.125rem (18px)
.mg-button-sm {
  padding: var(--ui-spacing-sm) var(--ui-spacing-md);
  font-size: var(--ui-typography-size-code);
}
.mg-button-md {
  padding: var(--ui-spacing-md) var(--ui-spacing-lg);
  font-size: var(--ui-typography-size-body);
}
.mg-button-lg {
  padding: var(--ui-spacing-lg) var(--ui-spacing-xl);
  font-size: 1.125rem;
}

6.3 Block Button

.mg-button-block {
  width: 100%;
}

6.4 Icon and Label Containers

The icon container uses inline-flex with line-height: 0 to eliminate line-height influence. SVG or iconify icons inside are forced to block display with width/height set to 1em.

.mg-button-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  line-height: 0;
}
.mg-button-icon svg,
.mg-button-icon .iconify {
  display: block;
  width: 1em;
  height: 1em;
}
.mg-button-label {
  display: inline-flex;
  align-items: center;
}

6.5 Solving Icon-Only Button Centering

When a button has only an icon and no text, the empty .mg-button-label occupies space and breaks centering. Hide empty labels with the :empty pseudo-class:

.mg-button-label:empty {
  display: none;
}

Also check for real content before rendering the label:

const hasLabel = computed(() => !!props.label || !!slots.default);

<span v-if="hasLabel" class="mg-button-label">
  <slot>{{ label }}</slot>
</span>

6.6 Variant Styles

filled and outline variants correspond to filled background and transparent background with border, respectively. Colors are dynamically combined via the color prop. For example, .mg-button-filled-primary uses --ui-primary as background color.

VII. Accessibility

Add ARIA attributes to improve accessibility:

<button
  :aria-busy="loading"
  :aria-disabled="disabled || loading"
>

Screen readers can correctly read the button's loading and disabled states.

VIII. Attribute Inheritance

Use v-bind="$attrs" to pass through native attributes:

<button v-bind="$attrs">

Users can directly pass attributes like id, name, data-*, aria-*:

<Button id="submit-btn" name="submit" data-testid="submit">
  Submit
</Button>

IX. Final Code

<template>
  <button
    v-bind="$attrs"
    class="mg-button"
    :class="[
      `mg-button-${variant}-${color}`,
      `mg-button-${size}`,
      { 'mg-button-block': block, 'mg-button-loading': loading },
    ]"
    :disabled="disabled || loading"
    :aria-busy="loading"
    :aria-disabled="disabled || loading"
    @click="handleClick"
  >
    <template v-if="loading">
      <span class="mg-button-loading-icon" />
    </template>

    <template v-else>
      <span v-if="hasIconSlot" class="mg-button-icon">
        <slot name="icon" />
      </span>
      <span v-if="hasLabel" class="mg-button-label">
        <slot>{{ label }}</slot>
      </span>
    </template>
  </button>
</template>

<script setup lang="ts">
import { useSlots, computed } from "vue";

const slots = useSlots();
const hasIconSlot = computed(() => !!slots.icon);
const hasLabel = computed(() => !!props.label || !!slots.default);

type Variant = "filled" | "outline";
type Color = "primary" | "success" | "warning" | "error";
type Size = "sm" | "md" | "lg";

interface Props {
  label?: string;
  variant?: Variant;
  color?: Color;
  size?: Size;
  disabled?: boolean;
  loading?: boolean;
  block?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  label: "",
  variant: "filled",
  color: "primary",
  size: "sm",
  disabled: false,
  loading: false,
  block: false,
});

const emit = defineEmits<{ click: [event: MouseEvent] }>();

const handleClick = (event: MouseEvent) => {
  if (props.disabled || props.loading) return;
  emit("click", event);
};
</script>

X. Comparison with Mainstream UI Libraries

API Feature Moongate UI Nuxt UI v4 Naive UI (NButton) PrimeVue (Button)
Core style variant (filled/outline) variant + color type severity + variant
Size size (sm/md/lg) size (xs/sm/md/lg/xl) size (small/medium/large) size (small/medium/large)
Disabled disabled disabled disabled disabled
Loading loading loading / loadingAuto loading loading
Block block block block fluid
Icon #icon slot icon / leading-icon / trailing-icon + slot None icon + iconPos
Extra styles None square dashed, circle, round rounded, raised, outlined

The comparison clearly shows:

  • Decoupling variant and color: variant focuses on "visual mode", color focuses on "semantic meaning"
  • Streamlined sizing: 3 sizes are sufficient for personal blog scenarios
  • Icon flexibility: The #icon slot achieves the same effect as props, with more flexibility
  • Semantic naming: Using filled and outline more accurately describes the visual style

XI. Additional Detail: The Width Change Trap in Loading State

There's a common but easily overlooked issue when using the loading attribute — "button width changes when loading". When the loading animation (e.g., a spinner) appears, it changes the button's internal children, usually causing the container to widen and layout shifts. This is essentially Cumulative Layout Shift (CLS).

An elegant solution: reserve space with min-width, and absolutely position the loading icon so it doesn't affect layout.

.mg-button {
  /* 1. Reserve enough space to ensure consistent width in loading and normal states */
  min-width: 88px;
}

.mg-button-loading .mg-button-label {
  opacity: 0;
}

.mg-button-loading-icon {
  /* 2. Absolutely position the loading icon centered, without affecting layout */
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

XII. Design Decision Summary

Decision Reason
Remove xs size Low usage frequency, simplify API
Remove ghost variant Can be replaced by outline
Remove neutral color Can be replaced by outline + default color
Default size sm Mainstream UI libraries default to ~32px
Only use #icon slot Avoid prop/slot confusion, keep it simple
label prop + default slot Support both writing styles
Hide empty label Solve icon-only button centering
v-bind="$attrs" Pass through native attributes, maintain flexibility
min-width + absolute positioned loading icon Prevent layout shift during loading

© 2026 yuelinghuashu. This work is licensed under CC BY-NC 4.0.