当前位置:网站首页>The principle of v-model
The principle of v-model
2022-07-31 10:37:00 【yibucuo】
v-model绑定input框
v-model 本质上不过是语法糖,可以用 v-model 指令在表单 <input>、<textarea> 及 <select> 元素上创建双向数据绑定.它会根据控件类型自动选取正确的方法来更新元素.它负责监听用户的输入事件以更新数据,并对一些极端场景进行一些特殊处理.v-model 会忽略所有表单元素的 value、checked、selected 特性的初始值而总是将 Vue 实例的数据作为数据来源.你应该通过 JavaScript 在组件的 data 选项中声明初始值.v-model 在内部为不同的输入元素使用不同的属性并抛出不同的事件:text 和 textarea 元素使用 value 属性和 input 事件;checkbox 和 radio 使用 checked 属性和 change 事件;select 字段将 value 作为 prop 并将 change 作为事件.
<input v-model="searchText">
<input v-bind:value="searchText" v-on:input="searchText = $event.target.value" >
<!-- 自html5开始,input每次输入都会触发oninput事件, 所以输入时input的内容会绑定到searchText中,于是searchText的值就被改变; $event 指代当前触发的事件对象; $event.target 指代当前触发的事件对象的dom; $event.target.value 就是当前dom的value值; 在@input方法中,value => searchText; 在:value中,searchText => value; -->
v-model绑定input组件
v-model绑定一个value值,and customize oneinput事件v-on:input=“searchText = $event.target.value”
<KInput v-model="userInfo.username" placeholder="请输入用户名"></KInput>
组件内部,接受到value值,在用户触发input自带的input事件后,于是触发onInput,进一步this.$emit(‘input’),This triggers the above bindinginput事件,执行了searchText = $event.target.value
<template>
<div>
<input :type="type" :value="value" @input="onInput">
</div>
</template>
<script> export default {
props: {
value: {
type: String, default: '' }, type: {
type: String, default: 'text' } }, methods: {
onInput(e) {
// 这里就是v-model的原理,派发一个input事件即可 this.$emit('input', e.target.value) } }, } </script>
边栏推荐
猜你喜欢

单点登录原理及实现方式

Redis缓存面临的缓存雪崩问题

NowCoderTOP28-34 binary tree - continuous update ing

初识二叉搜索树

Implement a thread pool

What does "chmod 777-R filename" mean?

Chapter VII

Day113. Shangyitong: user authentication, Alibaba Cloud OSS, patient management

Open Kylin openKylin automation developer platform officially released

【JWT】JWT 整合
随机推荐
Principle of Redis Sentinel
Redis Cluster - Sentinel Mode Principle (Sentinel)
Use turtle to draw buttons
Meikle Studio--Hongmeng 14-day development training notes (8)
Chapter VII
WSL2安装.NET 6
Centos7 install mysql5.7
Sql优化总结!详细!(2021最新面试必问)
力扣shell刷题
WEB核心【记录网站登录人数,记录用户名案例】Cookie技术实现
SQLSERVER merges subquery data into one field
浅谈Attention与Self-Attention,一起感受注意力之美
Usage of exists in sql
C#之泛型、委托、事件及其使用
Build finished with errors/Executable Not Found
湖仓一体电商项目(二):项目使用技术及版本和基础环境准备
Data Middle Office Construction (6): Data System Construction
【LeetCode】387. 字符串中的第一个唯一字符
可以用聚酯树脂将接线板密封接线盒吗?(接线盒灌封胶用哪种树脂)
《云原生的本手、妙手和俗手》——2022全国新高考I卷作文