v-model 双向绑定
v-model
是用于 <input>、<textarea> 、<select>
元素、以及自定义 components
上实现数据双向绑定功能的的指令。
1. 什么是双向绑定?
vue
中给提供了一个 v-model
指令,它可以使绑定的数据变化是更新对应的视图,视图中数据变化时能改变对应的数据
2. 常用修饰符有哪些?
lazy
取代input
监听change
事件number
将输入的字符串转为有效的数字trim
过滤输入首尾的空格
3. v-model 的实现?
4. 自定义组件中使用 v-model
4.1 自定义组件内部使用
v-model
是一个语法糖,默认情况相当于 :value
与 @input
,即:
html
<input v-model="val" type="text" />
<!-- @input 是 input 的原生事件,用户输入时触发, change 事件是失去焦点时触发 -->
<input :value="val" @input="val = $event.target.value" />
<input v-model="val" type="text" />
<!-- @input 是 input 的原生事件,用户输入时触发, change 事件是失去焦点时触发 -->
<input :value="val" @input="val = $event.target.value" />
4.2 父子组件间使用
例如:
HTML
<demo-count v-model="count" />
<demo-count v-model="count" />
HTML
<button @click="$emit('click', value + 1)">点我value+1</button>
<button @click="$emit('click', value + 1)">点我value+1</button>
JS
{
props: {
value: {
}
},
model:{
prop: value, // 默认值为 value
event: click // 默认值为 input
}
}
{
props: {
value: {
}
},
model:{
prop: value, // 默认值为 value
event: click // 默认值为 input
}
}