1.创建组件
xtx-checkbox.vue
<template>
<div class="xtx-checkbox" @click="changeChecked()">
<i v-if="checked" class="iconfont icon-checked"></i>
<i v-else class="iconfont icon-unchecked"></i>
<span v-if="$slots.default"><slot /></span>
</div>
</template>
<script>
import { ref } from 'vue'
export default {
name: 'XtxCheckbox',
setup () {
const checked = ref(false)
const changeChecked = () => {
checked.value = !checked.value
}
return { checked, changeChecked }
}
}
</script>
<style scoped lang="less">
.xtx-checkbox {
display: inline-block;
margin-right: 2px;
.icon-checked {
color: @xtxColor;
~ span {
color: @xtxColor;
}
}
i {
position: relative;
top: 1px;
}
span {
margin-left: 2px;
}
}
</style>
2.实现双向绑定
vue3.0中v-model会拆解成 属性 modelValue 和 事件 update:modelValue
import { ref, watch } from 'vue'
// v-model ====> :modelValue + @update:modelValue
export default {
name: 'XtxCheckbox',
props: {
modelValue: {
type: Boolean,
default: false
}
},
setup (props, { emit }) {
// const checked = ref(false)
const changeChecked = () => {
// checked.value = !checked.value
emit('update:modelValue', !props.modelValue)
}
return { changeChecked }
}
}
3.测试
Playground/index.vue
<div>
<div @click="isAgree=!isAgree">创建二级类目</div>
{{isAgree}}
<xtx-checkbox v-model="isAgree">同意吗?</xtx-checkbox>
</div>
<script>
setup () {
const isAgree = ref(false)
return { isAgree }
}
</script>
4.在sort.vue中补充使用复选框组件
<template>
<!-- 排序区域 -->
<div class='sub-sort'>
// 省略其他...
<div class="check">
<XtxCheckbox v-model="sortParams.inventory">仅显示有货商品</XtxCheckbox>
<XtxCheckbox v-model="sortParams.onlyDiscount">仅显示特惠商品</XtxCheckbox>
</div>
</div>
</template>