vue自定义组件实现v-model

314 阅读1分钟

实现原理

1,自定义组件从props接收value值,为避免组件内部直接修改value,于是将value赋值给组件内部的currentValue,组件内部在修改currentValue得同时,通过$emit('input', currentValue)向外部提交修改的值,也就是将组件内部的值同步到父组件中。
2,vue默认接收的值和提交事件是valueinput,如果想自定义这两个值,可以在model选项中修改,参考下面得例子

参考代码

<template>
    <div></div>
</template>
<script>
    export default {
        name: 'customComponent',
        components: {},
        props: {
            value: {
                type: String,
                default: '',
            },
        },
        model: {
            prop: 'value',
            event: 'input',
        },
        data() {
            return {
                currentValue: this.value,
            };
        },
        watch: {
            value: newValue => {
                this.currentValue = newValue;
            },
            currentValue: newValue => {
                this.$emit('input', newValue);
            },
        },
    };
</script>

   <custom-component v-model="test" />