vue父子組件的雙向綁定實現方式


最近 做組件封轉的時候用到了父子組件之間的數據雙向綁定問題,主要應用場景為:

1、在實現一個具有插槽效果的彈出框時,控制彈出框顯示的show值變為true 若是直接通過props傳給子組件,子組件雖然打開了彈出框,但是子組件關閉彈出框=>即子組件接收父組件的show變為false后,因為組件參數的傳遞是單向的,父組件的show並沒有被變成false,所以導致了彈出框只能被打開一次的情況出現。

這時候,就需要實現父子組件之間的show值的雙向綁定才能對彈出框顯示關閉的自由控制。

解決示例:

父組件調用<Dialog >子組件:

    <div class="dialogBox">
      <el-button @click="show = true">openDialog</el-button>
      <Dialog :visible.sync='show' width='30%' :buttonsGrounpSwitch="true"></Dialog>
    </div>

子組件:

    <div v-cloak id="dialog">
      <el-dialog :title="title" :visible.sync="show" :width="width" :close-on-click-modal='false' :show-close='false'>
        <div>彈出框內容</div>

        <div slot="footer" class="dialog-footer">
          <div v-if="!buttonsGrounpSwitch">
            <el-button v-if="isShowCancel" @click="cancel">{{cancelText}}</el-button>
            <el-button type="primary" @click="ack">{{ackText}}</el-button>
          </div>
        </div>

      </el-dialog>
    </div>

    props:{

      visible : {
        type : Boolean,
        default:false
      },

    }

    data(){
      return{
        show : false
      }
    },

    watch: {
      visible() {
         this.show = this.visible;
      },
    },

      methods:{

      cancel(){
        this.show = false;
        //雙向綁定show 同步更改父組件的visible值
        this.$emit('update:visible',this.show);
      },
      ack(){
        this.show = false;
        //雙向綁定show 同步更改父組件的visible值
        this.$emit('update:visible',this.show);
      }

    }

    

父組件中在傳show值時在參數名后添加.sync 修飾符,在子組件中的關閉事件中加入this.$emit('update:visible',false);廣播false給父級添加了修飾符的參數實現雙向綁定。可以在父級使用觀察者模式觀察子組件關閉后父組件show值是否同步變化。

 

 

2、做搜索欄組件時,父組件的一個v-model參數與搜索子組件實現搜索關鍵字的雙向綁定。

示例如下 :

父組件 :

  <SearchBar v-model="searchKey"></SearchBar>

子組件props使用value接受父組件v-model的搜索關鍵字:

  props:{
    value : {
      type: String,
      required: true
    }
  }

  使用watch觀察者模式監聽關鍵字輸入的變化:

  watch : {

    value() {
      this.searchKey = this.value;
    },

  },

  methods:{
    inputSearch(){
      this.$emit('input',this.searchKey);
    },
  },

  將變化的值實時賦值給子組件內部真實的搜索關鍵字searchKey之后使用 this.$emit('input', this.searchKey);實時調用input事件廣播子組件關鍵字


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM