vue3使用 VueUse useVModel

文章介绍了Vue3中的useVModel如何实现在父组件与子组件之间的双向数据绑定,包括如何传递属性、使用v-model语法以及自定义回调。
摘要由CSDN通过智能技术生成

1、useVModel()的作用
用于父子组件共享数据,

1、父组件有个flag(Boolean)属性
2、将flag属性传递给子组件,要实现双向数据绑定
3、flag属性在子组件发生变化,父组件的flag属性一起改变

2、如何使用
父组件app.vue

<template>
    <div>
        <uniInput v-model:flag="flag" @update:flag="tofather"></uniInput>
    </div>
</template>
 
<script setup>
import uniInput from './components-input/uni-input.vue'
import {ref} from 'vue'
const flag=ref(true)
const tofather=(data)=>{
    console.log('data',data)
}
</script>
 
<style scoped lang="less"></style>

1、父组件有flag属性,使得flag和子组件uniInput双向绑定
2、使用v-model:flag进行双向绑定,v-model的默认写法是(v-model:modelValue),其中modelValue是传递到子组件的props值
3、@update:flag是子组件中的flag发生改变,执行的回调函数
4、tofather函数的参数 data是flag改变时,回调函数传递的参数

子组件uniInput.vue

<template>
    <div>
      <h1>{{ flag }}</h1>
      <button @click="changeflag">点击事件</button>
    </div>
</template>
 
<script setup lang="ts">
import {defineProps,defineEmits} from 'vue'
import {useVModel} from '@vueuse/core'
const emit=defineEmits([])
const props=defineProps({
  flag:{
    type:Boolean,
    default:false
  }
})
 
const flag=useVModel(props,'flag',emit)
 
const changeflag=()=>{
  flag.value=!flag.value
}
</script>
 
<style scoped lang="less"></style>

1、引入useVModel
2、使用props接收父组件传递的值(接收flag)
3、用useVModel()函数,传参props,双向绑定的flag,emit
4、当执行changeflag函数时,检测到flag被修改,会默认执行回调函数update:flag,不会在代码中体现
5、默认执行emit(‘update:flag’,flag),参数是当前双向绑定的值

3、一般情况
多数情况下,使用v-model都是如下使用,不带名称

<uniInput v-model="flag"></uniInput>

所以在子组件使用如下方式接收,因为v-model默认名称是modelValue

const props=defineProps({
  modelValue:{
    type:Boolean,
    default:false
  }
})

同理使用useVModel()如下

const flag=useVModel(props,'modelValue',emit)

当flag改变时,默认调用update:modelValue的emit,所以接收回调如下

<uniInput v-model="flag" @update:model-value="tofather"></uniInput>

总结
useVModel()用来实现父子组件间数据的双向绑定,若不想使用默认回调,也可以自己使用emit实现回调

其他文档可参考:
vue3使用 VueUse useVModel
我常用的几个 VueUse 组合,推荐给你们!

传递一个对象:

子组件:

<el-input v-model="params.prompt" placeholder="请输入歌词" clearable />
<el-input v-model="params.tags" placeholder="请输入类型" clearable />
<el-input v-model="params.title" placeholder="请输入歌名" clearable />
<script setup lang="ts">
import { useVModels } from '@vueuse/core'
const emit = defineEmits<{
    (event: 'update:modelValue', params: string): void
}>()
const props = withDefaults(
    defineProps<{
        modelValue?: any
    }>(),
    {
        modelValue: ''
    }
)
const { modelValue: params } = useVModels(props, emit)
</script>

父组件:

<prompt-txt2img v-model="drawForm"></prompt-txt2img>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值