关于javascript:Vue.js-v模型与v绑定之间的区别

Vue.js—Difference between v-model and v-bind

我正在通过在线课程学习Vue,导师给了我一个练习,使输入文本具有默认值。 我使用v-model完成了此操作,但是讲师选择了v-bind:value,但我不明白为什么。

有人可以给我一个简单的解释,关于两者之间的区别,什么时候最好使用它们?


从这里 -
记得:

1
<input v-model="something">

本质上与以下内容相同:

1
2
3
4
<input
   v-bind:value="something"
   v-on:input="something = $event.target.value"
>

或(简写语法):

1
2
3
4
<input
   :value="something"
   @input="something = $event.target.value"
>

因此v-model是表单输入的双向绑定。它结合了v-bind(将js值带入标记)和v-on:input来更新js值。

如果可以,请使用v-model。必要时使用v-bind / v-on :-)我希望您的回答被接受。

v-model适用于所有基本的HTML输入类型(文本,文本区域,数字,单选,复选框,选择)。如果模型将日期存储为ISO字符串(yyyy-mm-dd),则可以将v-modelinput type=date一起使用。如果您想在模型中使用日期对象(一旦您要对它们进行操作或设置格式,这是一个好主意),请执行此操作。

v-model有一些其他的聪明之处,很容易意识到。如果您使用的是IME(很多移动键盘,或者中文/日文/韩文),则v-model不会更新,直到单词完整(输入空格或用户离开字段)为止。 v-input将更频繁地触发。

v-model还具有修饰符.lazy.trim.number,已在文档中进行了介绍。


简单来说
v-model是两种绑定方式:如果更改输入值,则绑定的数据将被更改,反之亦然。

但是v-bind:value被称为一种方式绑定,这意味着:您可以通过更改绑定数据来更改输入值,但是不能通过通过元素更改输入值来更改绑定数据。

看看这个简单的例子:https://jsfiddle.net/gs0kphvc/


模型
这是两种方式的数据绑定,它用于在更改输入值时绑定html输入元素,然后绑定的数据将被更改。

v模型仅用于HTML输入元素

1
ex: <input type="text" v-model="name">

绑定
这是数据绑定的一种方式,意味着您只能将数据绑定到输入元素,而不能更改绑定的数据更改输入元素。
v-bind用于绑定html属性
例如:

1
 click me


1
2
3
4
5
6
7
8
9
10
v-model is for two way bindings means: if you change input value, the bound data will be changed and vice versa. but v-bind:value is called one way binding that means: you can change input value by changing bound data but you can't change bound data by changing input value through the element.

v-model is intended to be used with form elements. It allows you to tie the form
 element (e.g. a text input) with the data object in your Vue instance.

Example: https://jsfiddle.net/jamesbrndwgn/j2yb9zt1/1/

v-bind is intended to be used with components to create custom props. This allows you to pass data to a component. As the prop is reactive, if the data that’s passed to the component changes then the component will reflect this change

 Example: https://jsfiddle.net/jamesbrndwgn/ws5kad1c/3/

希望这对您有基本的了解


在某些情况下,您不想使用v-model。如果您有两个输入,并且每个输入都相互依赖,则可能会有循环引用问题。常见的用例是您要构建会计计算器。

在这些情况下,使用观察者或计算属性不是一个好主意。

取而代之的是,将您的v-model拆分成上面的答案所示

1
2
3
4
<input
   :value="something"
   @input="something = $event.target.value"
>

在实践中,如果您以这种方式将逻辑去耦,则可能会调用一个方法。

这是真实情况下的样子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js">


  <input :value="extendedCost" @input="_onInputExtendedCost" />
  <p>
 {{ extendedCost }}



  var app = new Vue({
    el:"#app",
    data: function(){
      return {
        extendedCost: 0,
      }
    },
    methods: {
      _onInputExtendedCost: function($event) {
        this.extendedCost = parseInt($event.target.value);
        // Go update other inputs here
    }
  }
  });