我正在制作一个InputWrapper组件,用于装饰一些 BootstrapVue 输入组件。重点是围绕给定输入自动处理验证状态、消息、样式等(未在下面的示例中显示)。
我想动态地“转发” v-model。当包装的组件使用自定义模型属性和更新事件进行双向绑定时,就会出现问题。
主要思想如下。
InputWrapper.Vue
<template>
<div>
<slot v-bind="wrappedBindings"></slot>
</div>
</template>
<script>
export default {
props: {
value: {required: true}
},
methods: {
onInput($event){
this.$emit('input', $event);
}
},
computed: {
wrappedBindings(){
return {
attrs: {
value: this.value
},
on: {
input: $event => this.onInput($event),
'update:value': $event => this.onInput($event)
}
}
}
}
}
</script>
用法
<div>
<input-wrapper v-model="selectModel" v-slot="{attrs, on}">
<!-- v-model of b-form-select is :value and @input so this works -->
<b-form-select v-bind="attrs" v-on="on" ...other stuff...></b-form-select>
</input-wrapper>
<input-wrapper v-model="inputModel" v-slot="{attrs, on}">
<!-- v-model of b-form-input is :value and @update (not @update:value or @input) so this does not work -->
<b-form-input v-bind="attrs" v-on="on" ...other stuff...></b-form-input>
</input-wrapper>
<input-wrapper v-model="checkModel" v-slot="{attrs, on}">
<!-- v-model of b-form-checkbox is :checked (not :value) and @input so this does not work -->
<b-form-checkbox v-bind="attrs" v-on="on" ...other stuff...></b-form-checkbox>
</input-wrapper>
</div>
我目前和不满意的解决方案
<div>
<input-wrapper v-model="inputModel" v-slot="{attrs, on}">
<b-form-input v-bind="attrs" v-on="on" @update="on.input"
...other stuff...></b-form-input>
</input-wrapper>
<input-wrapper v-model="checkModel" v-slot="{attrs, on}">
<b-form-checkbox v-bind="attrs" v-on="on" :checked="attrs.value"
...other stuff...></b-form-checkbox>
</input-wrapper>
</div>
这个解决方案让我可以做我想做的事,但它的实施时间更长,而且你总是需要附近的 BootstrapVue 文档。
另一种解决方案是为每个 BsVue 输入创建一个自定义组件,但我还需要将每个属性和事件转发到自定义组件。不这样做的原因有很多,但主要是更难维护。
我的问题如下:如何在事先不知道它们的情况下使用 v-bind="attrs" 和 v-on="on" 动态绑定任何自定义 v-model 属性和事件?