vue 实现value赋值
在 Vue 中实现 value 赋值
使用 v-model 实现双向绑定
在 Vue 中,可以通过 v-model 指令实现表单元素与数据的双向绑定。例如:
<template>
<input v-model="inputValue" />
</template>
<script>
export default {
data() {
return {
inputValue: ''
}
}
}
</script>
当用户在输入框中输入内容时,inputValue 会自动更新;反之,修改 inputValue 的值也会反映到输入框中。
使用 :value 实现单向绑定
如果需要只实现数据的单向绑定(从数据到视图),可以使用 :value:
<template>
<input :value="inputValue" @input="inputValue = $event.target.value" />
</template>
<script>
export default {
data() {
return {
inputValue: ''
}
}
}
</script>
这种方式需要手动监听 input 事件来更新数据。

在自定义组件中实现 v-model
在自定义组件中实现 v-model,需要在组件内部定义一个 model 选项:
<template>
<custom-component v-model="componentValue" />
</template>
<script>
export default {
data() {
return {
componentValue: ''
}
}
}
</script>
在自定义组件中:

<template>
<input :value="value" @input="$emit('input', $event.target.value)" />
</template>
<script>
export default {
props: ['value']
}
</script>
使用 .sync 修饰符
Vue 还提供了 .sync 修饰符来实现父子组件间的双向绑定:
<template>
<custom-component :value.sync="componentValue" />
</template>
<script>
export default {
data() {
return {
componentValue: ''
}
}
}
</script>
在自定义组件中:
<template>
<input :value="value" @input="$emit('update:value', $event.target.value)" />
</template>
<script>
export default {
props: ['value']
}
</script>
使用计算属性实现复杂赋值
对于需要复杂逻辑的赋值操作,可以使用计算属性:
<template>
<input v-model="computedValue" />
</template>
<script>
export default {
data() {
return {
rawValue: ''
}
},
computed: {
computedValue: {
get() {
return this.rawValue
},
set(value) {
this.rawValue = value.toUpperCase()
}
}
}
}
</script>
这种方式可以在赋值时添加额外的逻辑处理。






