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

