当前位置:首页 > 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 实现方案 使用开源库实现 推荐使用 mind-elixir 或 jsmind 这类开源库,它们专为脑图设计且支持 Vue 集成。 安装依赖: npm install mi…

vue实现下拉框删除

vue实现下拉框删除

Vue 实现下拉框删除功能 在Vue中实现下拉框的删除功能通常涉及以下步骤: 数据绑定与渲染 在Vue组件中定义数据数组用于存储下拉框选项: data() { return { op…

vue实现跑车

vue实现跑车

Vue 实现跑车动画效果 使用 Vue 结合 CSS 动画可以实现跑车在屏幕上移动的效果。以下是一个完整的实现方案: 创建 Vue 组件结构 <template> <div c…

vue实现级联

vue实现级联

Vue 实现级联选择器的方法 级联选择器(Cascader)是常见的表单组件,用于处理多层级联动数据选择(如省市区选择)。以下是几种实现方式: 基于 Element UI 的 el-cascader…

vue页面实现

vue页面实现

Vue 页面实现方法 创建 Vue 组件 使用 Vue 单文件组件(SFC)方式创建页面,文件扩展名为 .vue。一个基本的 Vue 组件包含三个部分:模板(template)、脚本(script)和…

甘特图vue实现

甘特图vue实现

甘特图 Vue 实现方法 使用开源库 vue-ganttastic 安装依赖: npm install vue-ganttastic 基础实现代码: <template> <…