美文网首页
自定义组件实现 v-model

自定义组件实现 v-model

作者: McDu | 来源:发表于2021-03-27 11:23 被阅读0次

我们要实现自定义组件的双向绑定,其实需要的功能其实是:

组件内部可以接收并同步父组件传入的value值
组件内部可以在该双向绑定值修改时emit一个input事件

我们知道,直接修改父组件传入的值(prop)是不被允许的,
而且需要在双向绑定值于组件内部修改时拦截其操作,改为向父组件emit事件,
那么使用计算属性的get()、set()来写再合适不过了。

  1. parentComp.vue
<template>
    <childComp v-model="foo"></childComp>
</template>

<script>
export default {
    data() {
        return {
            foo: 1
        };
    }
};
</script>
  1. childComp.vue
<template>
    <input v-model="currentValue">
</template>

<script>
import TwoWay from "path/to/two-way.js";

export default {
     prop: ['value'],
     computed: {
        currentValue: {
            get() {
                return this.value;
            },
            set(newVal) {
                this.$emit('input', newVal);
            }
        }
    },
    mounted() {
        this.currentValue = 2;
    }
};
</script>

自定义组件v-model的最简洁实现 - 基础篇

相关文章

网友评论

      本文标题:自定义组件实现 v-model

      本文链接:https://www.haomeiwen.com/subject/winehltx.html