Elementui el-input 實現自定義 v-model


Vue 本身支持自定義組件實現 v-model ,但 el-input 作為 Elementui 的自定義組件也已經實現 v-model ,那么如果在自定義組件中使用 el-input ,但自定義組件也想實現 v-model ,應該怎么做?


 

錯誤的方式

  1. Vue 中讓自定義組件實現 v-model 可參考 Vue自定義v-model
  2. 但如果按照這種方式想要讓以下代碼實現 v-model ,是不可取的
    • 可以用,但每次在頁面第一次渲染的時候都沒有值,非要手動輸入一次,才會觸發變化
    • 這是因為下面這個 in-player 組件中的 el-input 已經實現了自定義的 v-model ,當 in-player 再次通過同樣的方式實現時,就出現了兩次 watch 操作
 
<template>
  <div class="in-player-panel">
    <el-input placeholder="請輸入視頻vid" v-model="videoId">
      <el-button slot="append" @click="changePlayAuth">播放</el-button>
    </el-input>
  </div>
</template>

<script type="text/ecmascript-6">
  export default {
    name: 'in-player',
    props: {
      value: {
        type: String,
        value: ' '
      }
    },
    data () {
      return {
        videoId: ''
      }
    },
    watch: {
      'value' (val) {
        if (val == this.videoId) { return false }
        this.videoId = val
      },
      'videoId' (val) { this.$emit('input', val) }
    }
  }
</script>

 

正確的方式

  1. 如果在自定義組件中,既想使用 el-input 的樣式和規則,又想讓組件本身實現自定義 v-model
  2. 那么就應該像如下代碼一樣,不直接使用 el-input 的 v-model 實現,轉而使用其 @input 函數


 
<template>
  <div class="in-player-panel">
    <el-input placeholder="請輸入視頻vid" :value="value" @input="update">
      <el-button slot="append" @click="changePlayAuth">播放</el-button>
    </el-input>
  </div>
</template>

<script type="text/ecmascript-6">
  export default {
    name: 'in-player',
    props: {
      value: {
        type: String,
        value: ' '
      }
    },
    methods: {
      update (val) {
        this.$emit('input', val)
      }
    }
  }
</script>

 


免責聲明!

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



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