Vue3项目中useVModel的使用方式

23 篇文章 1 订阅

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>

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值