溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么在vue中利用v-model實(shí)現(xiàn)跨組件綁定

發(fā)布時間:2021-04-29 15:52:58 來源:億速云 閱讀:158 作者:Leah 欄目:開發(fā)技術(shù)

怎么在vue中利用v-model實(shí)現(xiàn)跨組件綁定?相信很多沒有經(jīng)驗(yàn)的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。

1:簡單版代碼如下:

父組件:

<template>
  <div>
  // 3:使用子組件,并使用v-model綁定
    <About v-model="father"/>
  </div>
</template>

<script>
// 1:引入子組件
import About from "./About";
export default {
// 2:注冊子組件
  components: {
    About,
  },
  data() {
      return {
      // 值給空
          father:''
      }
  },
  // 監(jiān)聽組件數(shù)據(jù)的變化
  watch:{
      father(val){
          console.log(val);
      }
  }
};
</script>

子組件:

<template>
  <div>
  // 2:使用v-model綁定
      <input type="text" v-model="son">
  </div>
</template>

<script>
export default {
    // 1:接收父組件的信息
    props: {
        value:{
            type:String,
            default:''
        }
    },
    data() {
        return {
        // 3:賦空值
            son:''
        }
    },
    // 4:監(jiān)聽 如果改變
    watch:{
        // 把value賦值給son   
        value(){
        // 這里的this.value是props里的value
            this.son = this.value
        },
        // 把son傳遞給父組件
        son(){
            this.$emit('input',this.son)
        }
    }
}
</script>

至于為什么子組件向父組件傳遞時,$emit的第一個參數(shù)為'input',有興趣的同行可以去了解一下v-model實(shí)現(xiàn)的原理

2:下面進(jìn)入項(xiàng)目中的使用(獲取子組件的圖片地址,傳給父組件,同步更新圖片信息)

基本上差不多

Ⅰ:在父組件內(nèi)引入子組件,并在子組件標(biāo)簽內(nèi)使用v-model,賦值為空
(UploadImg標(biāo)簽 是引入的 子組件)

怎么在vue中利用v-model實(shí)現(xiàn)跨組件綁定

Ⅱ:接著在子組件內(nèi)使用 props接收:

怎么在vue中利用v-model實(shí)現(xiàn)跨組件綁定

Ⅲ:在子組件 頁面 內(nèi)同樣使用v-model,并在data內(nèi)賦值為空 圖片:

怎么在vue中利用v-model實(shí)現(xiàn)跨組件綁定

Ⅳ:在子組件內(nèi)使用watch用來監(jiān)聽其變化

怎么在vue中利用v-model實(shí)現(xiàn)跨組件綁定

分解圖上代碼:

value函數(shù)把傳來的父組件賦值給子組件,this.value也就是props里的value

value() {
      this.SonStaffPhoto = this.value
      console.log(this.SonStaffPhoto)
    }

這里是v-model綁定的子組件函數(shù),用來把自己傳遞給父組件

SonStaffPhoto() {
      this.$emit('input', this.SonStaffPhoto)
    },

到這里你就可以把想傳遞給父組件的內(nèi)容賦值給 this.SonStaffPhoto了(我賦值給了用來保存圖片地址的變量)

Ⅴ:也可以在父組件里監(jiān)聽其變化:

怎么在vue中利用v-model實(shí)現(xiàn)跨組件綁定

父組件里的this.staffPhoto,同樣可以把想綁定的內(nèi)容賦值給它(我賦值給了最新的圖片變量,這樣就過實(shí)現(xiàn)了子組件圖片更新,父組件也同步更新的效果)

看完上述內(nèi)容,你們掌握怎么在vue中利用v-model實(shí)現(xiàn)跨組件綁定的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI