当前位置:网站首页>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>
边栏推荐
猜你喜欢
随机推荐
WEB核心【记录网站登录人数,记录用户名案例】Cookie技术实现
面试、工作中常用sql大全(建议收藏备用)
恋爱期间的赠与能否撤销
Experience innovation and iteration through the development of a lucky draw applet
Module eight
【LeetCode】387. 字符串中的第一个唯一字符
【23提前批】北森云计算-测开面经
Three ways of single sign-on
【Go事】一眼看穿 Go 的集合和切片
SQL存储过程详解
Open Kylin openKylin automation developer platform officially released
突破传统可靠性测试:混沌工程优秀实践
Redis Cluster - Sentinel Mode Principle (Sentinel)
Redis的简单使用
小程序如何使用订阅消息(PHP代码+小程序js代码)
新人学习小熊派华为iot介绍
[Part 1 of Cloud Native Monitoring Series] A detailed explanation of Prometheus monitoring system
【LeetCode】203.移除链表元素
因存在自燃安全隐患,宝马7系和5系紧急召回,合计超过5.7万辆
乐观锁和悲观锁