Vue 3의 Props와 Computed로 기본 버튼 컴포넌트를 만들었다.😇🥳 보통 어떻게 만드는지 알 수 있으면 좋겠는데 찾기가 힘들어서 그냥 공식 문서 보면서 했다.
연습은 Vue 온라인 연습장에서 했다.
일단 Solid button, ghost button, outline button 세 가지만 나타나게 해보았다.
props로 어떤 버튼인지 btntype을 받아오면 해당 버튼에 맞는 class가 추가되게 하였다. Btn.vue에서 class로 버튼 종류를 나누어 style을 지정했다.
<style>에 scoped 속성을 추가하면 현재 컴포넌트의 앨리먼트에만 스타일이 적용된다.
[Btn.vue]
<template><div class="btn" :class="btnClass"><slot>Button</slot></div></template><script setup>import { computed } from 'vue';const props = defineProps({btntype: {type: String,default: 'solid'}})const btnClass = computed(() => {switch (props.btntype) {case 'solid':return 'solid-button';case 'ghost':return 'ghost-button';case 'outline':return 'outline-button';default:return '';}})</script><style scoped>.btn {padding: 8px 16px;border-radius: 4px;font-weight: 500;text-align: center;}.solid-button {background-color: green;color: white;}.ghost-button {color: green;border: 1px solid green;}.outline-button {background-color: white;color: green;border: 1px solid gray;}</style>
*앨리먼트 선택기에는 scoped를 사용하지 않아야 한다. 앨리먼트 선택기가 느려서 생긴 규칙이라고 한다.(참고) 처음엔 div에 직접 style을 지정했다가 클래스 선택기를 사용하도록 'class="btn"'을 추가해서 수정했다.
[App.vue]
<template><div class="buttons"><Btn btntype="solid">Solid Button</Btn><Btn btntype="ghost">Ghost Button</Btn><Btn btntype="outline">Outline Button</Btn></div></template><script setup>import Btn from './Btn.vue'</script><style>.buttons {display: inline-flex;flex-direction: column;gap: 6px;}</style>
실행 결과
앞으로 사용할 버튼 종류가 많을텐데 이름을 헷갈리지 않게 정하는 것도 중요할 것 같다.

0 댓글