vue.js自定義組件實(shí)現(xiàn)v-model雙向數(shù)據(jù)綁定的示例代碼
我們都清楚v-model其實(shí)就是vue的一個(gè)語(yǔ)法糖,用于在表單控件或者組件上創(chuàng)建雙向綁定。
//表單控件上使用v-model
<template>
<input type="text" v-model="name" />
<input type="checkbox" v-model="checked"/>
<!--上面的input和下面的input實(shí)現(xiàn)的效果是一樣的-->
<input type="text" :value="name" @input="name=e.target.vlaue"/>
<input type="checkBox" :checked="checked" @click=e.target.checked/>
{{name}}
</template>
<script>
export default{
data(){
return {
name:"",
checked:false,
}
}
}
</script>
vue中父子組件的props通信都是單向的。父組件通過(guò)props向下傳值給子組件,子組件通過(guò)$emit觸發(fā)父組件中的方法。所以自定義組件是無(wú)法直接使用v-model來(lái)實(shí)現(xiàn)v-model雙向綁定的。那么有什么辦法可以實(shí)現(xiàn)呢?
//父組件
<template>
<div>
<c-input v-model="form.name"></c-input>
<c-input v-model="form.password"></c-input>
<!--上面的input等價(jià)于下面的input-->
<!--<c-input :value="form.name" @input="form.name=e.target.value"/>
<c-input :value="form.password" @input="form.password=e.target.value"/>-->
</div>
</template>
<script>
import cInput from "./components/Input"
export default {
components:{
cInput
},
data() {
return {
form:{
name:"",
password:""
},
}
},
}
</script>
//子組件 cInput
<template>
<input type="text" :value="inputValue" @input="handleInput">
</template>
<script>
export default {
props:{
value:{
type:String,
default:"",
required:true,
}
},
data() {
return {
inputValue:this.value,
}
},
methods:{
handleInput(e){
const value=e.target.value;
this.inputValue=value;
this.$emit("input",value);
},
}
}
</script>
根據(jù)上面的示例代碼可以看出,子組件c-input上綁定了父組件form的值,在子組件中通過(guò):value接收了這個(gè)值,然后我們?cè)谧咏M件中修改了這個(gè)值,并且通過(guò)$emit觸發(fā)了父組件中的input事件將修改的值又賦值給了form。
綜上就實(shí)現(xiàn)了自定義組件中的雙向數(shù)據(jù)綁定!
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Vue中的父子組件通訊以及使用sync同步父子組件數(shù)據(jù)
這篇文章主要介紹了Vue中的父子組件通訊以及使用sync同步父子組件數(shù)據(jù),對(duì)vue感興趣的同學(xué),可以參考下2021-04-04
Vuex進(jìn)行Echarts數(shù)據(jù)頁(yè)面初始化后如何更新dom
這篇文章主要為大家詳細(xì)介紹了使用Vuex做Echarts數(shù)據(jù)時(shí),當(dāng)頁(yè)面初始化后如何更新dom,文中的示例代碼講解詳細(xì),有需要的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-11-11
詳解Vue單元測(cè)試Karma+Mocha學(xué)習(xí)筆記
本篇文章主要介紹了詳解Vue單元測(cè)試Karma+Mocha學(xué)習(xí)筆記,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-01-01
三步搞定:Vue.js調(diào)用Android原生操作
這篇文章主要介紹了三步搞定:Vue.js調(diào)用Android原生操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-09-09
vue.js引用背景圖background無(wú)效的3種解決方案
這篇文章主要介紹了vue.js引用背景圖background無(wú)效的3種解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08
基于elementUI使用v-model實(shí)現(xiàn)經(jīng)緯度輸入的vue組件
這篇文章主要介紹了基于elementUI使用v-model實(shí)現(xiàn)經(jīng)緯度輸入的vue組件,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-05-05
vue開發(fā)之LogicFlow自定義業(yè)務(wù)節(jié)點(diǎn)
這篇文章主要為大家介紹了vue開發(fā)之LogicFlow自定義業(yè)務(wù)節(jié)點(diǎn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01

