说明:
在我们的前端表单提交的时候我们可能需要做一些根据input框中值的改变响应式的传给我们的javascript变量进行事件的处理,我们自己手动的去绑定或者去定义一个事件的时候很麻烦,所以我们可以通过v-model指令为我们自动来做这些事情
基本用法
文本
<template>
<view>input输入的值:{{text}}</view>
<input type="text" v-model="text" class="inputStyle">
</template>
<script setup>
import {ref} from "vue";
const text = ref('');
</script>
多行文本
<template>
<text style="margin-left: 20px;">多行文本的值:</text>
<view style="white-space: pre-line;margin-left: 20px;">{{textArea}}</view>
<textarea v-model="textArea" style="border: 1px solid black;margin-left: 10px;"></textarea>
</template>
<script setup>
import {ref} from "vue";
const textArea=ref('');
</script>
修改《Vue3条件渲染》中的案例
没用v-model之前的做法:
<template>
<view style="margin-top: 20px;">
请输入今天星期几(阿拉伯数字1-7):<input type="text" @input="onChangeInputValue" :class="'inputStyle'">
<!-- @input文本框输入的时候触发的事件 -->
</view>
<view v-if="num>=1 && num<=7">
{{days[num-1]}}
</view>
<view v-else>格式错误</view>
</template>
<script setup>
import {ref} from "vue";
const num = ref();
const days=ref(["星期一","星期二","星期三","星期四","星期五","星期六","星期天"])
function onChangeInputValue(e) {
//为num赋文本框的值,以用于组件的判断
num.value = parseInt(e.detail.value);
}
</script>
<style lang="scss" scoped>
.inputStyle {
display: inline-block;
vertical-align: middle;
margin-left: 5px;
border: 1px solid black;
width: 70px;
}
</style>
使用v-model改造代码后的代码:
<template>
<view style="margin-top: 20px;">
请输入今天星期几(阿拉伯数字1-7):<input type="text" v-model="num" :class="'inputStyle'">
<!-- @input文本框输入的时候触发的事件 -->
</view>
<view v-if="num>=1 && num<=7">
{{days[num-1]}}
</view>
<view v-else>格式错误</view>
</template>
<script setup>
import {ref} from "vue";
const num = ref("");
const days=ref(["星期一","星期二","星期三","星期四","星期五","星期六","星期天"])
</script>
<style lang="scss" scoped>
.inputStyle {
display: inline-block;
vertical-align: middle;
margin-left: 5px;
border: 1px solid black;
width: 70px;
}
</style>
从这两个代码中可以看出使用了v-model的代码少了@input的监听事件,而是直接通过v-model响应式的修改script的变量