Vue 本身支持自定義組件實(shí)現(xiàn) v-model ,但 el-input 作為 Elementui 的自定義組件也已經(jīng)實(shí)現(xiàn) v-model ,那么如果在自定義組件中使用 el-input ,但自定義組件也想實(shí)現(xiàn) v-model ,應(yīng)該怎么做?
更多精彩
- 更多技術(shù)博客,請(qǐng)移步 IT人才終生實(shí)訓(xùn)與職業(yè)進(jìn)階平臺(tái) - 實(shí)訓(xùn)在線
錯(cuò)誤的方式
- Vue 中讓自定義組件實(shí)現(xiàn) v-model 可參考 Vue自定義v-model
- 但如果按照這種方式想要讓以下代碼實(shí)現(xiàn) v-model ,是不可取的
- 可以用,但每次在頁(yè)面第一次渲染的時(shí)候都沒(méi)有值,非要手動(dòng)輸入一次,才會(huì)觸發(fā)變化
- 這是因?yàn)橄旅孢@個(gè) in-player 組件中的 el-input 已經(jīng)實(shí)現(xiàn)了自定義的 v-model ,當(dāng) in-player 再次通過(guò)同樣的方式實(shí)現(xiàn)時(shí),就出現(xiàn)了兩次 watch 操作
<template>
<div class="in-player-panel">
<el-input placeholder="請(qǐng)輸入視頻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>
正確的方式
- 如果在自定義組件中,既想使用 el-input 的樣式和規(guī)則,又想讓組件本身實(shí)現(xiàn)自定義 v-model
- 那么就應(yīng)該像如下代碼一樣,不直接使用 el-input 的 v-model 實(shí)現(xiàn),轉(zhuǎn)而使用其
@input
函數(shù)
<template>
<div class="in-player-panel">
<el-input placeholder="請(qǐng)輸入視頻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>