当前位置:首页 > 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 实现v model

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

vue 实现v model

<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.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 实现矩阵的方法 在 Vue 中实现矩阵操作可以通过多种方式完成,以下是一些常见的方法: 使用二维数组表示矩阵 矩阵可以用二维数组来表示,每个元素对应矩阵中的一个值。在 Vue 的 data…

vue 实现复选

vue 实现复选

Vue 实现复选功能 在 Vue 中实现复选功能可以通过多种方式完成,以下是常见的几种方法: 使用 v-model 绑定数组 通过 v-model 绑定一个数组,可以自动收集用户选择的复选框值。…

实现vue模版

实现vue模版

Vue 模板的基本结构 Vue 模板基于 HTML 语法,通过 Vue 的指令和插值实现动态渲染。以下是一个基础模板示例: <template> <div id="app…

vue实现分类

vue实现分类

Vue实现分类功能的方法 使用v-for和计算属性 通过计算属性对数据进行分类处理,结合v-for渲染分类后的列表。示例代码: <template> <div>…

vue实现管道

vue实现管道

Vue 中实现管道(Pipe)功能 在 Vue 中可以通过过滤器(Filters)或计算属性(Computed Properties)实现类似管道的功能,将数据经过多个处理步骤后输出。 使用过滤器…

vue实现过滤

vue实现过滤

Vue实现过滤的方法 在Vue中实现数据过滤可以通过多种方式完成,以下是几种常见的方法: 使用计算属性过滤 计算属性是Vue中处理数据过滤的理想选择,它们基于响应式依赖进行缓存,只有在相关依赖发生改…