我正在使用第三方日期选择器组件。我为此组件创建了一个包装器,因此我可以设置一些适合我的应用程序的默认值。但是,我在通过模型时遇到了问题。如何确保模型的双向绑定(bind)?当我直接使用第三方组件时,一切正常。
我的页面.vue
<my-datepicker v-model="from"></my-datepicker>
my-datepicker.vue
<template>
<thirdparty-datepicker>
:value="value"
</thirdparty-datepicker>
</template>
<script>
export default {
props: {
value: {
value: String
}
}
}
</script>
编辑
根据 Bert 的意见,我设法让它开始工作。每次第三方组件上的日期发生变化时 input
事件被抛出。所要做的就是连接到该事件并重新发出它。
<template>
<thirdparty-datepicker>
:value="value"
v-on:input="change"
</thirdparty-datepicker>
</template>
<script>
export default {
props: {
value: {
value: String
}
},
methods: {
change (newValue) {
this.$emit('input', newValue)
}
}
}
</script>
最佳答案
为了在您的自定义组件上支持v-model
,您必须accept a value parameter and emit an input
event (尽管可以自定义;有关详细信息,请参见链接)。您的代码只做其中的一部分。您如何实现将取决于第三方组件的工作方式。
假设第三方组件发出了一个 change
事件。如果是这样,那么您将在第三方组件发出 change
时发出 input
。
<template>
<thirdparty-datepicker :value="value" @change="onChange">
</thirdparty-datepicker>
</template>
<script>
export default {
props: {
value: {
value: String
}
},
methods:{
onChange(newValue){
this.$emit('input', newValue)
}
}
}
</script>
关于javascript - 包装一个 VueJs 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44698993/