vue学习(十二)v-model

文章介绍了Vue3中v-model的工作原理,作为props和emit的语法糖,用于实现父子组件间的双向数据绑定。通过示例展示了如何使用v-model控制子组件的显示与隐藏,以及如何处理多个v-model绑定。同时,文中提到在Vue3中v-model的更新是破坏性的。
摘要由CSDN通过智能技术生成

在Vue3中 v-model 是破坏性更新的

v-model在组件里面也是很重要的

v-model 其实是一个语法糖  通过props 和 emit组合而成的

案例

点击父组件中的按钮开关,控制子组件显示框的显示与隐藏

父组件: 

<template>
    <h1>我是APP.vue父组件</h1>
    <div>isShow:{{isShow}}</div>
    <br>
    <button @click="change">开关</button>
    <hr>
    <vModel v-model="isShow"></vModel>
</template>

<script setup lang='ts'>
import {ref} from 'vue'
// 引入子组件
import vModel from './components/v-model/v-model.vue'
const isShow = ref<boolean>(true)
// 按钮点击事件 使子组件的显示或隐藏
const change = ()=>{
    isShow.value = !isShow.value
}
</script>

子组件

注意:prop:value -> modelValue

通过defineProps 接收 v-model传递的值 ===== modelValue

// 点击子组件的关闭按钮,改变modelValue的值,通过defineEmits并将值传递给父组件

<template>
<div class="dialog" v-if="modelValue">
    <button class="btn" @click="close">关闭</button>
    {{ modelValue }}
    <h2>我是v-model子组件  dialog</h2>
    <div>内容:<input type="text" @input="input"></div>
</div>
</template>

<script setup lang='ts'>
defineProps<{
    modelValue:boolean,
}>()
const emit = defineEmits(['update:modelValue'])
// 点击子组件的关闭按钮,改变modelValue的值,并将值传递给父组件
const close = ()=>{
    emit('update:modelValue',false)
}
</script>

<style scoped lang="less">
.dialog{
    position: relative;
    width: 500px;
    height: 150px;
    border: 5px solid #999;
    padding: 0 10px;
    display: flex;
    flex-direction:column;
    .btn{
        position: absolute;
        top: 10px;
        right: 10px;
    }
}
</style>

 绑定多个案例

父组件

<template>
    <h1>我是APP.vue父组件</h1>
    <div>isShow:{{isShow}}</div>
    <div>text:{{ text }}</div>
    <br>
    <button @click="change">开关</button>
    <hr>
    <vModel v-model="isShow" v-model:textVal="text"></vModel>
</template>
<script setup lang='ts'>
import {provide, ref,readonly} from 'vue'
import vModel from './components/v-model/v-model.vue'
const isShow = ref<boolean>(true)
const change = ()=>{
    isShow.value = !isShow.value
}
const text = ref<string>('春分')
</script>
<style scoped>
</style>

子组件

<template>
<div class="dialog" v-if="modelValue">
    <button class="btn" @click="close">关闭</button>
    {{ modelValue }}
    <h2>我是v-model子组件  dialog</h2>
    <div>内容:<input type="text" :value="textVal" @input="input"></div>
</div>
</template>
<script setup lang='ts'>
const props = defineProps<{
    modelValue:boolean,
    textVal:string,
}>()
const emit = defineEmits(['update:modelValue','update:textVal'])
const close = ()=>{
    emit('update:modelValue',false)
}
const input = (e:Event)=>{
    const target = e.target as HTMLInputElement
    emit('update:textVal', target.value)
}
</script>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值