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>

猜你喜欢

转载自blog.csdn.net/Linlietao0587/article/details/128349975
今日推荐