我们要实现自定义组件的双向绑定,其实需要的功能其实是:
组件内部可以接收并同步父组件传入的value值
组件内部可以在该双向绑定值修改时emit一个input事件
我们知道,直接修改父组件传入的值(prop)
是不被允许的,
而且需要在双向绑定值于组件内部修改时拦截其操作,改为向父组件emit事件,
那么使用计算属性的get()、set()
来写再合适不过了。
- parentComp.vue
<template>
<childComp v-model="foo"></childComp>
</template>
<script>
export default {
data() {
return {
foo: 1
};
}
};
</script>
- 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>
网友评论