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" > |
因此
如果可以,请使用
简单来说
但是
看看这个简单的例子: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/ |
希望这对您有基本的了解
在某些情况下,您不想使用
在这些情况下,使用观察者或计算属性不是一个好主意。
取而代之的是,将您的
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 } } }); |