vue3表单输入绑定 v-model

vue3表单输入绑定 v-model

一、基本使用

1.1、v-model 使用

<template>
    <input type="text" v-model="msg"/>
    <h2>{{msg}}</h2>
</template>

<script setup>
import { ref} from 'vue'
const msg=ref("Hello World")
</script>

1.2、v-model原理

本质是两个操作
1、v-bind绑定一个value属性
2、v-on给当前元素添加一个input事件

<template>
    <h2>{{msg}}</h2>
    <input type="text" :value="msg" @input="changeValue" />
</template>

<script setup>
import { ref, reactive } from 'vue'
const msg=ref("Hello World")
//函数
function changeValue(e){
    msg.value=e.target.value
}
</script>

效果如同v-model

二、常见效果

2.1 复选 checkbox

  • 单选
    在这里插入图片描述
<template>
    <span>复选框checkbox</span>
    <input type="checkbox" v-model="checked" />
    <h2>{{checked}}</h2>
</template>

<script setup>
import { ref, reactive } from 'vue'
const checked=ref(true)
</script>
  • 多选
    在这里插入图片描述
<template>
    <!--多个勾选框-->
    <input type="checkbox" v-model="fruits" value="苹果" />苹果
    <input type="checkbox" v-model="fruits" value="梨子" />梨子
    <input type="checkbox" v-model="fruits" value="西瓜" />西瓜
    <h2>喜欢水果是:{{ fruits }}</h2>
</template>

<script setup>
import { ref, reactive } from 'vue'
const fruits = ref([])
</script>

2.2 单选 radio

在这里插入图片描述

<template>
    <input type="radio" v-model="sex" value="男"/><input type="radio" v-model="sex" value="女"/><h2>{{sex}}</h2>
</template>

<script setup>
import { ref, reactive } from 'vue'
const sex=ref('男')
</script>

2.3 下选框 select

  • 单选
    在这里插入图片描述
<template>
    <select name="" id="" v-model="city">
        <option value="深圳">深圳</option>
        <option value="揭阳">揭阳</option>
        <option value="惠州">惠州</option>
        <option value="广州">广州</option>
    </select>
    <h2>{{ city }}</h2>
</template>

<script setup>
import { ref, reactive } from 'vue'
const city = ref('')
</script>
  • 多选
    在这里插入图片描述
<template>
    <select name="" id="" v-model="citys" multiple>
        <option value="深圳">深圳</option>
        <option value="揭阳">揭阳</option>
        <option value="惠州">惠州</option>
        <option value="广州">广州</option>
    </select>
    <h2>{{ citys }}</h2>
</template>

<script setup>
import { ref, reactive } from 'vue'
const citys = ref([])
</script>

多选需要,按住ctrl或shift哦

三、修饰符使用

3.1 lazy

lazy,当输入框失去焦点,再去同步输入框中的数据

 <input type="text" v-model.lazy="msg">
 <h2>{{msg}}</h2>

3.2 number

number将输入框的内容自动转为数字类型

 <input type="text" v-model.number="counter">
 <h2>{{typeof counter}}</h2>

3.3 trim

trim自动过滤用户输入的首位空白字符

 <input type="text" v-model.trim="msg">
 <h2>{{msg}}</h2>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值