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的形式更直观简单~

猜你喜欢

转载自www.cnblogs.com/zhiying/p/11323082.html