首页 前端知识 useVModel()的使用------通俗易懂

useVModel()的使用------通俗易懂

2024-04-09 23:04:18 前端知识 前端哥 308 761 我要收藏

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实现回调 

转载请注明出处或者链接地址:https://www.qianduange.cn//article/4675.html
标签
评论
还可以输入200
共0条数据,当前/页
发布的文章

JQuery中的load()、$

2024-05-10 08:05:15

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!