search
HomeWeb Front-endJS TutorialWhat is the implementation principle of v-model? Introduction to how to use v-model (with code)

Vue中Vue-model原理是什么?v-model是Vue用于表单元素上创建双向数据绑定,它本质是一个语法糖,在单向数据绑定的基础上,增加了监听用户输入事件并更新数据的功能。下面的文章中将给大家说一说v-model的实现原理及其使用方法的介绍。

v-model实现原理

genDirectives

Vue初始化组件时通过genDirectives(el,state)初始化指令。(这里的el已经通过parseHTML将html结构转换成Vue的AST语法树,state是根据用户定义组件的options新建的CodegenState对象)。

<div>
    请输入:<input><br>
    你输入的是:<input>
</div>

当用户在html页面上写了v-model指令进行数据双向绑定,Vue通过state找到model指令对应的方法model(el,dir,_warn),并执行该方法。(这里双!!表示将函数返回结果转换成Boolean类型)

var gen = state.directives[dir.name];
    if (gen) {
      needRuntime = !!gen(el, dir, state.warn);
    }

model

if (el.component) {
    genComponentModel(el, value, modifiers);
    return false
  } else if (tag === 'select') {
    genSelect(el, value, modifiers);
  } else if (tag === 'input' && type === 'checkbox') {
    genCheckboxModel(el, value, modifiers);
  } else if (tag === 'input' && type === 'radio') {
    genRadioModel(el, value, modifiers);
  } else if (tag === 'input' || tag === 'textarea') {
    genDefaultModel(el, value, modifiers);
  } else if (!config.isReservedTag(tag)) {
    genComponentModel(el, value, modifiers);
    return false
  } else {
    warn$1(
      ": " +
      "v-model is not supported on this element type. " +
      'If you are working with contenteditable, it\'s recommended to ' +
      'wrap a library dedicated for that purpose inside a custom component.'
    );
  }

model()根据表单元素的tag标签以及type属性的值,调用不同的方法也就验证了官网所说的“随表单控件类型不同而不同。”这里调用的就是genDefaultModel().

genDefaultModel

var type = el.attrsMap.type;

获取表单元素的类型,此处type='text'.

{
    var value$1 = el.attrsMap['v-bind:value'] || el.attrsMap[':value'];
    var typeBinding = el.attrsMap['v-bind:type'] || el.attrsMap[':type'];
    if (value$1 && !typeBinding) {
      var binding = el.attrsMap['v-bind:value'] ? 'v-bind:value' : ':value';
      warn$1(
        binding + "=\"" + value$1 + "\" conflicts with v-model on the same element " +
        'because the latter already expands to a value binding internally'
      );
    }
  }

检测该表单元素是否同时有v-model绑定和v-bind:value。

  var ref = modifiers || {};
  var lazy = ref.lazy;
  var number = ref.number;
  var trim = ref.trim;
  var needCompositionGuard = !lazy && type !== 'range';
  var event = lazy
    ? 'change'
    : type === 'range'
      ? RANGE_TOKEN
      : 'input';

获取修饰符lazy,number及trim.

  • .lazy 取代input监听change事件

  • .number 输入字符串转为数字

  • .trim 输入首尾空格过滤

 var valueExpression = '$event.target.value';
  if (trim) {
    valueExpression = "$event.target.value.trim()";
  }
  if (number) {
    valueExpression = "_n(" + valueExpression + ")";
  }

定义变量valueExpression,本例子的情况valueExpression为'$event.target.value'。

var code = genAssignmentCode(value, valueExpression);
function genAssignmentCode (
  value,
  assignment
) {
  var res = parseModel(value);
  if (res.key === null) {
    return (value + "=" + assignment)
  } else {
    return ("$set(" + (res.exp) + ", " + (res.key) + ", " + assignment + ")")
  }
}

通过genAssignmentCode()方法生成v-model value值得代码。根据本文的例子返回的结果就是"message=$event.target.value"。

if (needCompositionGuard) {
    code = "if($event.target.composing)return;" + code;
  }

添加event.target.composing判断。event.target.composing用于判断此次input事件是否是IME构成触发的,如果是IME构成,直接return。IME 是输入法编辑器(Input Method Editor) 的英文缩写,IME构成指我们在输入文字时,处于未确认状态的文字。

带下划线的ceshi就属于IME构成,它会同样会触发input事件,但不会触发v-model更新数据。

addProp(el, 'value', ("(" + value + ")"));
function addProp (el, name, value) {
  (el.props || (el.props = [])).push({ name: name, value: value });
  el.plain = false;
}

给el添加prop

What is the implementation principle of v-model? Introduction to how to use v-model (with code)

addHandler(el, event, code, null, true);
function addHandler (el,name,value,modifiers,important,warn){
    /*其他代码省略*/
    var newHandler = {
        value: value.trim()
      };
    var handlers = events[name];
      if (Array.isArray(handlers)) {
        important ? handlers.unshift(newHandler) : handlers.push(newHandler);
      } else if (handlers) {
        events[name] = important ? [newHandler, handlers] : [handlers, newHandler];
      } else {
        events[name] = newHandler;
      }
}

将code作为el的对应event处理的方法handler,此处events['input']=if($event.target.composing)return;message =$event.target.value
最后原来的html结构就由:

<input>

变成了:

<input>

添加修饰符

如果添加了trim修饰符
原来的html结构就由:

<input>

变成了:

<input>

如果添加了lazy修饰符
原来的html结构就由:

<input>

变成了:

<input>

如果添加了number修饰符
原来的html结构就由:

<input>

变成了:

<input>

这里的_n是在installRenderHelpers里面定义的,指向toNumber方法。

function installRenderHelpers (target) {
  /*其他代码省略*/
  target._n = toNumber;
}

而toNumber就是使用parseFloat函数来转的数字,再使用isNaN判断转换结果,如果结果是NaN,那么就返回原字符串,否则返回转为数字后的结果:

function toNumber (val) {
  var n = parseFloat(val);
  return isNaN(n) ? val : n
}

注意:number修饰符不能限制输入的内容,就算输入的不是数字,也可能会被转换,如输入'1次测试',转换的结果就是1

相关文章推荐:

vue中v-model动态使用详解

vue v-model表单控件绑定的实例教程

Vue 进阶教程之:v-model的详解

The above is the detailed content of What is the implementation principle of v-model? Introduction to how to use v-model (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools