08 – Vue3 UI Framework – Input 組件
- 2021 年 12 月 16 日
- 筆記
- [00] UI Framework, [18] Vue, vue-project, vue.js
接下來再做一個常用的組件 –
input
組件返回閱讀列表點擊 這裡
需求分析
開始之前我們先做一個簡單的需求分析
input
組件有兩種類型,即input
和textarea
類型- 當類型為
textarea
時,可以自定義行高,但是當類型為input
時,行高恆為1
- 可以自定義外邊框的顏色
- 可以設置為禁用
那麼可以得到如下參數表格
參數 | 含義 | 類型 | 可選值 | 默認值 |
---|---|---|---|---|
value | 綁定值 | string | 字元串 | 必填 |
theme | 類型 | string | input / textarea | input |
rows | 行高,當 theme 為 input 時值恆為 1 | number | 正整數 | 5 |
color | 外邊框顏色 | string | 任意合法顏色值 | #8c6fef |
disabled | 是否禁用 | boolean | false / true | false |
骨架
實際上我們這裡是根據 theme
值判斷,然後去渲染原生的 input
或者 textarea
組件,所以可以很容易得到骨架,程式碼如下:
<template>
<input
v-if="theme === 'input'"
class="jeremy-input-input"
:style="{ '--color': color }"
v-model="text"
@input="change"
/>
<textarea
v-else
class="jeremy-input-textarea"
:rows="rows"
:style="{ '--color': color }"
v-model="text"
@input="change"
/>
</template>
功能
首先,我們再 Typescript
中聲明一些需求分析中的屬性:
declare const props: {
value: string;
theme?: "input" | "textarea";
rows?: number;
color?: string;
};
declare const context: SetupContext;
然後,再在 export default
中寫入聲明的參數:
export default {
install: function (Vue) {
Vue.component(this.name, this);
},
name: "JeremyInput",
props: {
value: {
type: String,
required: true,
},
theme: {
type: String,
default: "input",
},
rows: {
type: Number,
default: 5,
},
color: {
type: String,
default: "#8c6fef",
},
},
};
最後再補全 setup
:
setup(props, context) {
const text = ref(props.value);
const change = () => {
context.emit("update:value", text.value);
};
return { text, change };
},
樣式表
補全層疊樣式表
<style lang="scss">
$theme-color: var(--color);
[class^="jeremy-input"] {
resize: none;
padding: 8px;
border-radius: 4px;
border: none;
box-shadow: 0px 0px 3px 0px $theme-color;
outline: none;
width: 100%;
&[disabled] {
box-shadow: 0px 0px 3px 0px gray;
}
}
</style>
測試
創建一個測試頁,導入 JeremyInput
組件,看一下效果:
項目地址 🎁
GitHub: //github.com/JeremyWu917/jeremy-ui
官網地址 🌍
JeremyUI: //ui.jeremywu.top
感謝閱讀 ☕