自定義組件實現雙向綁定v-model


  自定義組件實現 v-model 雙向綁定,首先要先明白 v-model,這個指令到底實現了什么?

v-model實際做的事情就是:傳入一個value屬性值,雙向綁定會默認監聽input事件並返回一個值
在子組件 emit 一個 input 事件,並返回一個值,父組件調用 v-model 的時候會默認執行這個時間
舉個例子1:
  # 正常寫法
  <input type="text" v-model="userName" />
  # 等價於這種寫法
  <input type="text" :value="userName" @input="userName = $event.target.value" />

舉個例子2:
  # 自定義組件 <ButtonComponent /> 實現雙向綁定
    ButtonComponent組件的寫法:
    <button
      v-for="(item, index) in tabOptions"
      :key="item.$value"
      @click="handleTabSelect(item)">
      {{ item.$text }}
    </button>

    data:

      tabOptions = [{

        $text: "本地選擇",

        $value: "local"

      } , {

      $text: "COS選擇",

      $value: "cos"

      }] 

    methods:
      handleTabSelect(item) {

        // 子組件的input時間,當父組件的使用v-model的時候會觸發
        this.$emit('input', item.$value);
    }

  使用組件 <ButtonComponent /> 直接使用v-mode的方式就能讀取數據了

  <ButtonComponent v-model="tabValue" />

  等價於

  <ButtonComponent @input="handleValue"/>  

  data:

  tabValue="",

  methods:

  handleValue(value){

    this.tabValue = value;

  }


免責聲明!

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



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