search
HomeWeb Front-endJS TutorialAnalysis of v-model directive in Vue (with code)

Analysis of v-model directive in Vue (with code)

Jul 27, 2018 pm 01:07 PM
v-model directive

The content of this article is about the analysis of the v-model instruction in Vue (with code). It has a good reference value and I hope it can help friends in need.

1. Instruction explanation

v-model creates a two-way binding on a form control or component, which is essentially responsible for monitoring user input events (onchange, onkeyup, onkeydown, etc., which one specifically , please also check the official underlying implementation documentation) to update the data and perform some special processing for some extreme scenarios.

2. Form input binding methods and methods

2.1 Input box implements two-way data binding example:

<template>
  <div>
    <p class="p1">{{title}}</p>
    <div class="spancss1">
      <label>请输入:</label><input type="text" v-model="inputs"/><br/>
      <label>你在input框中输入了:</label><span>{{inputs}}</span>
    </div>
  </div>
</template>

<script>
    export default {
        name:"v-model",
      data(){
          return {
            title: &#39;v-model学习&#39;,
            inputs: &#39;&#39;
          }
      }
    }
</script>

<style scoped>
  .p1{
  text-align: left;
  }
  .spancss1{
      float: left;
      }
</style>

2.2 Textarea multiple Example of double-thinking data binding using line text:

<template>
  <div>
    <p class="p1">{{title}}</p>
    <div class="spancss1">
      <label>请输入:</label><textarea v-model="text"></textarea><br/>
      <label>你在textarea框中输入了:</label><span>{{text}}</span>
    </div>
  </div>
</template>

<script>
  export default {
    name:"v-model",
    data(){
      return {
        title: &#39;v-model学习&#39;,
        text: &#39;&#39;
      }
    }
  }
</script>

<style scoped>
  .p1{
    text-align: left;
  }
  .spancss1{
    float: left;
  }
</style>

2.3 Check box data binding

Single check box data binding Example:

<template>
  <div>
    <p class="p1">{{title}}</p>
    <div class="spancss1">
      <label>请输入:</label><input type="checkbox" id="checkbox" v-model="checked">选我<br/>
      <label v-if="checked">选中了:</label>
      <label v-if="!checked">没选中:</label>
      <span>{{ checked }}</span>
    </div>
  </div>
</template>

<script>
  export default {
    name:"v-model",
    data(){
      return {
        title: &#39;v-model学习&#39;,
        checked: &#39;&#39;
      }
    }
  }
</script>

<style scoped>
  .p1{
    text-align: left;
  }
  .spancss1{
    float: left;
  }
</style>

Multiple check boxes to implement data binding Example:

<template>
  <div>
    <p class="p1">{{title}}</p>
    <div class="spancss1">
      <label>请输入:</label>
      <input type="checkbox" id="vue1" value="vue1" v-model="checkedValues">vue1
      <input type="checkbox" id="vue2" value="vue2" v-model="checkedValues">vue2
      <input type="checkbox" id="vue3" value="vue3" v-model="checkedValues">vue3
      <br/>
      <label>选中了:</label><span>{{ checkedValues }}</span>
    </div>
  </div>
</template>

<script>
  export default {
    name:"v-model",
    data(){
      return {
        title: &#39;v-model学习&#39;,
        checkedValues: []
      }
    }
  }
</script>

<style scoped>
  .p1{
    text-align: left;
  }
  .spancss1{
    float: left;
  }
</style>

2.4 Radio buttons implement data binding, and the selected radio button value is obtained and displayed:

<template>
  <div>
    <p class="p1">{{title}}</p>
    <div class="spancss1">
      <input type="radio" id="radio1" value="1" v-model="checked">男<br/>
      <input type="radio" id="radio2" value="2" v-model="checked">女<br/>
      <label> 选中了:{{ checked }}</label>
    </div>
  </div>
</template>

<script>
  export default {
    name:"v-model",
    data(){
      return {
        title: &#39;v-model学习&#39;,
        checked: &#39;&#39;
      }
    }
  }
</script>

<style scoped>
  .p1{
    text-align: left;
  }
  .spancss1{
    float: left;
  }
</style>

2.5 Introduction to the selection box

Method 1: The selection box implements two-way data binding. First, the selection box implements a single selection. When the options in the radio button box set the disabled attribute, the options cannot be selected. When When the options in the radio button box have no value, the text of the options will be bound when the options are selected. When the options in the radio button box have a value, the value of the options will be bound when the options are selected. The example is as follows:

<template>
  <div>
    <p class="p1">{{title}}</p>
    <div class="spancss1">
      <select v-model="selected">
        <option disabled value="">请选择</option>
        <option>A</option>
        <option value="2">B</option>
        <option value="3">C</option>
      </select>
      <span>Selected: {{ selected }}</span>
    </div>
  </div>
</template>

<script>
  export default {
    name:"v-model",
    data(){
      return {
        title: &#39;v-model学习&#39;,
        selected: &#39;&#39;
      }
    }
  }
</script>

<style scoped>
  .p1{
    text-align: left;
  }
  .spancss1{
    float: left;
  }
</style>

Method 2 introduces the situation of multiple selections in the selection box. First, you need to add the multiple attribute to the select. When the options are in the radio button When setting the disabled attribute, this option cannot be selected. When the options in the radio button box have no value, the text of this option will be bound when this option is selected. When the options in the radio button box have a value, when this option is selected, The value of this options will be bound, then press the ctrl key and click on the options to be selected. A simple example is as follows:

<template>
  <div>
    <p class="p1">{{title}}</p>
    <div class="spancss1">
      <select v-model="selected" multiple>
        <option disabled value="">请选择</option>
        <option>A</option>
        <option value="2">B</option>
        <option value="3">C</option>
      </select>
      <span>Selected: {{ selected }}</span>
    </div>
  </div>
</template>

<script>
  export default {
    name:"v-model",
    data(){
      return {
        title: &#39;v-model学习&#39;,
        selected: []
      }
    }
  }
</script>

<style scoped>
  .p1{
    text-align: left;
  }
  .spancss1{
    float: left;
  }
</style>

3. v-model modifier

3.1 .lazy

By default, v-model synchronizes the value of the input box with the data after each input event is triggered. (Except when input method combines text). You can add the lazy modifier to switch to using onchange event is synchronized. When data is entered in the input box, the data will not change immediately. When the cursor leaves the input box, the data will be changed synchronously. The sample code is as follows:

<template>
  <div>
    <p class="p1">{{title}}</p>
    <div class="spancss1">
      <!-- 在“change”时而非“input”时更新 -->
      <input type="text" id="names" v-model.lazy="msg" ><br/>
      <label>输入值:</label>{{msg}}
    </div>
  </div>
</template>

<script>
  export default {
    name:"v-model",
    data(){
      return {
        title: &#39;v-model学习&#39;,
        msg: &#39;&#39;
      }
    }
  }
</script>

<style scoped>
  .p1{
    text-align: left;
  }
  .spancss1{
    float: left;
  }
</style>

3.2 .number

If you want to automatically convert the user’s input value to a numerical type, define type as number type and add the number modifier to v-model , when the user enters numerical type data, v-model.number will automatically convert the input data into a numerical type. Note that if the user enters the special letter e, the number attribute cannot be recognized. A simple code example is as follows:

<template>
  <div>
    <p class="p1">{{title}}</p>
    <div class="spancss1">
      <!-- 在“change”时而非“input”时更新 -->
      <input type="number" id="names" v-model.number="msg" ><br/>
      <label>输入值:</label>{{msg}}
    </div>
  </div>
</template>

<script>
  export default {
    name:"v-model",
    data(){
      return {
        title: &#39;v-model学习&#39;,
        msg: &#39;&#39;
      }
    }
  }
</script>

<style scoped>
  .p1{
    text-align: left;
  }
  .spancss1{
    float: left;
  }
</style>

3.3 .trim

If you want to automatically filter the leading and trailing blank characters entered by the user, you can add the trim modifier to v-model, in Add a few more spaces at the beginning of the input box. When the cursor leaves, the trim attribute will automatically filter the ending spaces. A simple code example is as follows:

<template>
  <div>
    <p class="p1">{{title}}</p>
    <div class="spancss1">
      <label>无trim属性</label>
      <input type="text" id="names" v-model="msg1" ><br/>
      <label>输入值:</label>{{msg1}}<br/>
      <label>有trim属性</label>
      <input type="text" id="names2" v-model.trim="msg2" ><br/>
      <label>输入值:</label>{{msg2}}
    </div>
  </div>
</template>

<script>
  export default {
    name:"v-model",
    data(){
      return {
        title: &#39;v-model学习&#39;,
        msg1: &#39;&#39;,
        msg2: &#39;&#39;
      }
    }
  }
</script>

<style scoped>
  .p1{
    text-align: left;
  }
  .spancss1{
    float: left;
  }
</style>

4. Used in components v-model

4.1 自定义组件v-model

一个组件上的 v-model 默认会利用名为 value 的 prop 和名为 input 的事件,但是像输入框、单选框、复选框等类型的输入控件可能会将 value 特性用于不同的目的。本文以自定义输入框和onchange事件为例,在输入框输入值,当光标离开以后输入值会输出绑定到置顶位置:

1. 在index中声明组件(在index声明的组件为全局组件,全局可用):

Vue.component('base-text', {
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    checked: Boolean
  },
  template: `<input>`
});
=

2. 在要使用该组件的插件中声明:

<template>
  <div>
    <p class="p1">{{title}}</p>
    <div class="spancss1">
     <base-text v-model="msg"></base-text><br/>
      <label>你输入了:</label>{{msg}}
    </div>
  </div>
</template>

<script>
  export default {
    name:"v-model",
    data(){
      return {
        title: &#39;v-model学习&#39;,
        msg: &#39;&#39;
      }
    }
  }
</script>

<style scoped>
  .p1{
    text-align: left;
  }
  .spancss1{
    float: left;
  }
</style>

3. 结果示例如下:

相关推荐:

对4-v-bind指令的分析(附代码)

The above is the detailed content of Analysis of v-model directive in Vue (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
Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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.

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

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor