当前位置:首页 > VUE

vue 实现v model

2026-01-19 14:47:23VUE

Vue 实现 v-model 的方法

Vue 的 v-model 是一个语法糖,用于在表单元素或自定义组件上实现双向数据绑定。以下是几种常见的实现方式:

在表单元素上使用 v-model

v-model 可以直接用于原生表单元素(如 inputtextareaselect),它会根据元素类型自动绑定对应的属性和事件。

<input v-model="message" placeholder="Edit me">
<p>Message is: {{ message }}</p>

对于复选框和单选按钮,v-model 会自动处理值的绑定:

<input type="checkbox" v-model="checked">
<p>Checked: {{ checked }}</p>

在自定义组件上使用 v-model

在自定义组件中,v-model 默认会绑定 value prop 和 input 事件。可以通过 model 选项修改默认行为。

<custom-input v-model="message"></custom-input>

自定义组件的实现:

Vue.component('custom-input', {
  props: ['value'],
  template: `
    <input
      :value="value"
      @input="$emit('input', $event.target.value)"
    >
  `
})

使用 .sync 修饰符

Vue 2.3.0+ 支持 .sync 修饰符,可以实现父子组件的双向绑定。

<custom-input :value.sync="message"></custom-input>

组件内部通过 $emit('update:value', newValue) 更新值:

Vue.component('custom-input', {
  props: ['value'],
  template: `
    <input
      :value="value"
      @input="$emit('update:value', $event.target.value)"
    >
  `
})

Vue 3 中的 v-model

Vue 3 对 v-model 进行了改进,支持多个 v-model 绑定,并默认使用 modelValueupdate:modelValue

<custom-input v-model="message"></custom-input>

组件实现:

app.component('custom-input', {
  props: ['modelValue'],
  template: `
    <input
      :value="modelValue"
      @input="$emit('update:modelValue', $event.target.value)"
    >
  `
})

自定义 v-model 修饰符

可以自定义 v-model 的修饰符,例如 trimnumber 等。

<input v-model.trim="message">

在自定义组件中,可以通过 model 选项的 propevent 字段自定义绑定行为:

vue 实现v model

Vue.component('custom-input', {
  model: {
    prop: 'value',
    event: 'change'
  },
  props: ['value'],
  template: `
    <input
      :value="value"
      @input="$emit('change', $event.target.value)"
    >
  `
})

通过以上方法,可以灵活地在 Vue 中实现 v-model 的双向绑定功能。

标签: vuemodel
分享给朋友:

相关文章

vue实现引导

vue实现引导

Vue 实现引导功能的方法 使用第三方库 推荐使用 driver.js 或 intro.js 这类专门为 Vue 设计的引导库。这些库提供了完整的 API 和样式,能够快速实现引导功能。 安装 dr…

vue实现类别

vue实现类别

Vue 实现类别的几种方法 在 Vue 中实现类别功能可以通过多种方式完成,以下是一些常见的方法: 使用 v-bind:class 动态绑定类名 通过对象语法或数组语法动态绑定类名,根据条件添加或移…

vue实现水印

vue实现水印

Vue 实现水印的方法 使用 CSS 背景图 通过 CSS 的 background-image 和 background-repeat 属性实现水印效果。创建一个包含水印文本的 Canvas,将其转…

vue实现数组

vue实现数组

Vue 实现数组操作的方法 在 Vue 中,数组的操作需要特别注意响应式的问题。Vue 提供了一些方法来确保数组的变动能够触发视图更新。 响应式数组方法 Vue 对以下数组方法进行了封装,确保它们能…

vue 实现全屏

vue 实现全屏

Vue 实现全屏功能 在 Vue 中实现全屏功能可以通过浏览器提供的 Fullscreen API 完成。以下是一个完整的实现方案: 安装依赖(可选) 如果需要跨浏览器兼容性更好,可以安装…

vue登录实现

vue登录实现

Vue 登录实现 实现登录功能通常需要前端与后端配合,Vue 作为前端框架,主要负责表单处理、请求发送和状态管理。以下是常见的实现方式: 表单设计与数据绑定 使用 Vue 的 v-model 实现表…