怎么在vue.js中實(shí)現(xiàn)v-model雙向數(shù)據(jù)綁定-創(chuàng)新互聯(lián)

本篇文章為大家展示了怎么在vue.js中實(shí)現(xiàn)v-model雙向數(shù)據(jù)綁定,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過(guò)這篇文章的詳細(xì)介紹希望你能有所收獲。

創(chuàng)新互聯(lián)堅(jiān)持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:成都網(wǎng)站設(shè)計(jì)、網(wǎng)站制作、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時(shí)代的連平網(wǎng)站設(shè)計(jì)、移動(dòng)媒體設(shè)計(jì)的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!

我們都清楚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。

上述內(nèi)容就是怎么在vue.js中實(shí)現(xiàn)v-model雙向數(shù)據(jù)綁定,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

名稱欄目:怎么在vue.js中實(shí)現(xiàn)v-model雙向數(shù)據(jù)綁定-創(chuàng)新互聯(lián)
網(wǎng)頁(yè)地址:http://bm7419.com/article32/ddjgpc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供定制開發(fā)、面包屑導(dǎo)航、網(wǎng)頁(yè)設(shè)計(jì)公司商城網(wǎng)站、靜態(tài)網(wǎng)站、網(wǎng)站設(shè)計(jì)公司

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

成都app開發(fā)公司