Vue组件可以使用v-model实现双向数据绑定。
在组件中,可以在props中定义一个value属性,并在组件中的对应位置使用v-model进行绑定。例如:
Copy
<template>
<div>
<input :value="value" @input="$emit('input', $event.target.value)">
</div>
</template>
<script>
export default {
props: {
value: {
type: String,
required: true
}
}
}
</script>
然后在使用该组件的地方,可以使用v-model进行绑定并传递数据:
Copy
<template>
<div>
<custom-component v-model="inputData"></custom-component>
</div>
</template>
<script>
export default {
data() {
return {
inputData: ''
}
}
}
</script>
这样,当输入框中的值改变时,inputData的值也会同步更新。同时,对inputData的值进行修改也会反映到输入框中。