日拱一卒-Vue中自定義組件如何實現v-model

前幾天面試的時候被問到了這個問題,不會。
今天工做的時候恰好有需求要用到,研究了一下。面試

首先要明白,所謂的v-model其實是一個語法糖。this

<child v-model="value"></child>

等於code

<child :value="value" @input="someHandler"></child>

所以,咱們須要在子組件中,使用props來接收value,以及用this.$emit來傳值出去。
在子組件中的寫法是這樣子的:get

// 這裏props不推薦這種寫法,只是demo使用
props: ["value"],
// 經過props拿到數據後,不要直接使用,而是要放在computed裏面使用纔是比較規範的寫法
computed: {
    computedValue: {
        get(){
            return this.value;
        },
        set(value){
            this.$emit("input",value);
        }
    }
}
相關文章
相關標籤/搜索