1. input 的 v-model 語法糖
首先我們需要了解v-model的原理
<template>
<div id="test">
## 使用v-model 將input 的值與official綁定,實(shí)現(xiàn)了雙向數(shù)據(jù)綁定
<input type="text" v-model="official" />
## 下面是v-model的原理,基于 v-bind 和 v-on 封裝的語法糖,$event.target獲取事件源,實(shí)現(xiàn)了雙向數(shù)據(jù)
<input type="text" v-bind="custom" v-on:input="custom = $event.target.value" />
</div>
</template>
<script>
export default {
data() {
return {
official: "",
custom: ""
};
}
};
</script>
2.v-model綁定自定義組件
有時候我要需要暴露出組件內(nèi)的值,使用v-model是最簡易的方法
一個組件上的
v-model默認(rèn)會利用名為value的 prop 和名為input的事件,但是像單選框、復(fù)選框等類型的輸入控件可能會將value特性用于不同的目的。model選項可以用來避免這樣的沖突
關(guān)于Prop可以查看這篇文章 http://www.itdecent.cn/p/67f2de4f47bf
## 子組件內(nèi)
<template>
<div>
<el-input v-model="input" @input="search" placeholder="請輸入內(nèi)容"></el-input> //綁定 input 事件 checked 和
</div>
</template>
<script>
export default {
name:"searchInput",
data() {
return {input: ""}},
model: {
prop: "value",
event: "change"
},
props: {
value: { //value 和 model內(nèi)prop的值一致
type: String,
default: ""
}
},
methods: {
search(event) {
this.$emit('change',event) //事件名和model內(nèi)event的值一致
}
}
};
</script>
##父組件內(nèi)
<search-input v-model="getValue"><search-input> //getValue的值將會傳入子組件名為 value的 prop
【有收獲請點(diǎn)個贊哦~~】