創建一個新的Button組件文件 Button.vue
:
<template><button :class="buttonClass" :disabled="disabled" @click="handleClick"><slot></slot><i v-if="icon" :class="icon"></i></button>
</template><script lang="ts">
import { defineComponent } from 'vue';interface ButtonProps {size?: 'small' | 'medium' | 'large';type?: 'primary' | 'secondary' | 'danger';link?: string;disabled?: boolean;icon?: string;
}export default defineComponent({name: 'MyButton',props: {size: {type: String,default: 'medium',},type: {type: String,default: 'primary',},link: {type: String,default: '',},disabled: {type: Boolean,default: false,},icon: {type: String,default: '',},},computed: {buttonClass(): string {return ['my-button',`my-button--${this.size}`,`my-button--${this.type}`,{ 'my-button--disabled': this.disabled },].join(' ');},},methods: {handleClick(event: MouseEvent): void {if (this.link) {window.location.href = this.link;}// 如果不需要跳轉,可以取消默認行為// event.preventDefault();},},
});
</script><style scoped>
.my-button {/* 基本樣式 */
}.my-button--small {/* 小按鈕樣式 */
}.my-button--medium {/* 中等按鈕樣式 */
}.my-button--large {/* 大按鈕樣式 */
}.my-button--primary {/* 主要按鈕樣式 */
}.my-button--secondary {/* 次要按鈕樣式 */
}.my-button--danger {/* 危險按鈕樣式 */
}.my-button--disabled {/* 禁用按鈕樣式 */
}
</style>
在這個組件中,定義了一個ButtonProps
接口來描述組件的屬性,并使用defineComponent
來創建組件。組件的props
屬性定義了組件的輸入屬性,包括size
、type
、link
、disabled
和icon
。還定義了一個計算屬性buttonClass
來動態生成按鈕的類名,以及一個handleClick
方法來處理按鈕的點擊事件。
在模板中,使用v-bind
指令來綁定按鈕的類名和禁用狀態,使用v-if
指令來根據icon
屬性是否存在來顯示圖標,使用@click
指令來監聽按鈕的點擊事件,并使用<slot></slot>
來插入按鈕的內容。
最后,在<style>
標簽中定義了按鈕的樣式,使用了scoped
屬性來確保樣式只應用于當前組件。
可以將這個組件導入到其他Vue組件中使用:
<template><div><MyButton size="large" type="danger" icon="fas fa-exclamation-triangle">警告按鈕</MyButton></div>
</template><script lang="ts">
import { defineComponent } from 'vue';
import MyButton from './Button.vue';export default defineComponent({components: {MyButton,},
});
</script>
關注微信公眾號溫暖前端,不定期分享前端知識點和前端資料↓↓↓