Vue——組件上使用v-model


一、最近在工作過程中要實現一個搜索模糊匹配功能,考慮到組件的復用,就單獨把搜索框抽出來作為一個子組件。在以往的開發中,我一般會在input框中的值變化時向父組件emit一個事件,並帶上一些父組件中需要的參數(比如搜索的關鍵詞,或者搜索之后返回的結果)

大概的實現方式如下:

父組件
<template>
    <div>
        <search @test="getData"></search>
        <button @click="submit">提交</button>
    </div>
</template>
<script>
import search from '@/components/index/search.vue'
export default {
    data() {
        return {
            keywords: ''
        }
    },
    components: {
        search
    },
    methods: {
        getData(val){
            this.keywords = val
        },
        submit() {
            console.log('keywords:', this.keywords)
        }
    }
}
</script>


子組件
<template>
    <div>
        <input @input="inputChange" type="text" name="keywords">
    </div>
</template>
<script>
export default {
    props: ['keywords'],
    methods: {
        inputChange(e) {
            this.$emit('test', e.target.value)
        }
    }
}
</script>

 

二、這次在實現的時候,我隱約記得在之前看Vue api的時候提到過,給組件添加v-model,就想用這種方式嘗試一下,根據官網解釋我理解:

v-model這個雙向綁定相當於做了兩個操作:(1)給當前這個組件添加了一個value屬性 (2)給當前這個組件綁定了一個input事件;由此我修改實現方式如下:

父組件:

<template>
    <div>
        <search v-model="keywords"></search>
        <button @click="submit">提交</button>
    </div>
</template>
<script>
import search from '@/components/index/search.vue'
export default {
    data() {
        return {
            keywords: ''
        }
    },
    components: {
        search
    },
    methods: {
        submit() {
            console.log('keywords:', this.keywords)
        }
    }
}
</script>

 

子組件:

<template>
    <div>
        <input :value="value" @input="$emit('input', $event.target.value)" type="text" name="keywords">
    </div>
</template>
<script>
export default {
    props: ['value']
}
</script>

 三、總結:其實兩種思路是一樣的,都是子組件通過emit事件向父組件傳值,但是v-model的形式更直觀簡單~


免責聲明!

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



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