当前位置:网站首页>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>
边栏推荐
猜你喜欢
随机推荐
【LeetCode】141.环形链表
Hospital management system database, course design, SQLserver, pure code design
SQL study notes - REGEXP operator
双链表的插入和删除
浅谈Attention与Self-Attention,一起感受注意力之美
实现弹框组件
【LeetCode】73.矩阵置零
Meikle Studio--Hongmeng 14-day development training notes (8)
FCN中制作自己的数据集并进行训练
NowCoderTOP23-27 Binary tree traversal - continuous update ing
【JWT】JWT 整合
GCD简单了解
C#之泛型、委托、事件及其使用
单点登录原理及实现方式
In half a month, MySQL has been consolidated again, and a tens of thousands of words "super hard core" article has been sorted out!
SQLServer2019安装(Windows)
如何优雅的停止一个线程?
darknet 源码阅读笔记-01-activation_kernels.cu
Android安全专题(三)JNI混淆
KVM virtualization job