vue3.0中v-model会拆解成 属性 modelValue 和 事件 update:modelValue
父组件:
<div class="check">
<XtxCheckbox v-model="sortParams.inventory">仅显示有货商品</XtxCheckbox>
<XtxCheckbox v-model="sortParams.onlyDiscount">仅显示特惠商品</XtxCheckbox>
</div>
子组件接收数据:
<template>
<div class="xtx-checkbox" @click="checked=!checked">
<!-- 选中的图标 -->
<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 { toRef } from 'vue'
import { useVModel } from '@vueuse/core'
export default {
name: 'XtxCheckbox',
props: {
modelValue: {
type: Boolean,
default: false
}
},
setup (props, { emit }) {
// useVModel函数代理了父子之间的数据交互
const checked = useVModel(props, 'modelValue', emit)
// const changeChecked = () => {
// checked.value = !checked.value
// }
return { checked }
}
// setup (props, { emit }) {
// // 选中与否的状态位
// const checked = toRef(props, 'modelValue')
// const changeChecked = () => {
// // checked.value = !checked.value
// // 修改modelValue的值
// emit('update:modelValue', !props.modelValue)
// }
// 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>