復(fù)選框的效果在網(wǎng)頁(yè)中很常見(jiàn),那么你知道復(fù)選框是如何實(shí)現(xiàn)的嗎?
一.封裝的意義
- 復(fù)用性更好
- 代碼可維護(hù)性
- 可以擴(kuò)展其他業(yè)務(wù)
二.準(zhǔn)備
- 使用的字體為阿里的iconfont上的字體圖標(biāo)資源,將需要的圖標(biāo)添加到購(gòu)物車(chē),然后把文件夾下載到本地,
在src/static/iconfont.js(把文件夾中的eiconfont.js,添加到static目錄下),用svg 導(dǎo)入圖標(biāo)
<svg v-if="checked" class="icon icon-checked" aria-hidden="true">
<use xlink:href="#icon-fuxuankuang1"></use>
</svg>
- 終端中執(zhí)行
yarn add @vueuse/core@5.3.0,這里安裝指定版本,各位按需選擇。
三.如何封裝
- 封裝
在src/libs/CheckBox.vue(這是復(fù)選框的通用組件基本構(gòu)建)
代碼如下示例:
<template>
<div class="my-checkbox" @click="changeChecked">
<svg v-if="checked" class="icon icon-checked" aria-hidden="true">
<use xlink:href="#icon-fuxuankuang1"></use>
</svg>
<svg v-else class="icon icon-unchecked" aria-hidden="true">
<use xlink:href="#icon-fangkuang"></use>
</svg>
<span v-if="$slots.default"><slot /></span>
</div>
</template>
<script lang="ts">
import { useVModel } from "@vueuse/core";
import { ref } from "vue";
export default {
props: {
modelValue: {
type: Boolean,
default: false,
},
},
setup(props, { emit }) {
//獲取父組件傳遞過(guò)來(lái)的值
const checked = useVModel(props, "modelValue", emit);
return { checked };
},
// setup(props, { emit }) {
// 選中與否的狀態(tài)位
// const checked = ref(props.modelValue);
// const changeChecked = () => {
// checked.value = !checked.value;
// 修改modelValue的值
// emit("update:modelValue", !props.modelValue);
// };
// return { checked, changeChecked };
// },
};
</script>
<style lang="scss">
$color: #27ba9b;
.my-checkbox {
display: inline-block;
&:last-child {
margin-left: 30px;
}
.icon-checked {
color: $color;
~ span {
color: $color;
}
}
svg {
font-size: 20px;
position: relative;
top: 1px;
}
span {
margin-left: 5px;
font-size: 20px;
}
}
</style>
- 使用
任意.vue結(jié)尾文件中使用,標(biāo)簽中的內(nèi)容會(huì)放置在標(biāo)簽中的內(nèi)容會(huì)放置在封裝的全局插件的默認(rèn)插槽中,各位可根據(jù)需求定制。
代碼如下(示例):
<template>
<h1>Checkbox組件示例</h1>
<div class="demo">
<h2>常規(guī)用法</h2>
<div class="demo__component">
<CheckBox v-model="isSelect.checked">復(fù)選框 勾選</CheckBox>
<CheckBox v-model="isSelect.noChecked">復(fù)選框 取消勾選</CheckBox>
</div>
<div class="demo__actions">
<Button>隱藏代碼</Button>
</div>
<div v-if="false" class="demo__code">
<pre>代碼</pre>
</div>
</div>
</template>
<script>
import CheckBox from "../libs/CheckBox.vue";
import Button from "../libs/Button.vue";
import { reactive } from "vue";
export default {
components: {
CheckBox,
Button,
},
setup() {
const isSelect = reactive({
checked: true,
noChecked: false,
});
return { isSelect };
},
};
</script>
<style lang="scss">
</style>
四. 效果演示

復(fù)選框效果圖.png
總結(jié)
Always believe that efforts will be rewarded