目录

基本用法

底层机制

v-model 的参数

多个 v-model 绑定

处理 v-model 修饰符

带参数的 v-model 修饰符

例子

总结:Vue 3 中的 v-model 指令与 Vue 2 中的 v-model 相比有一些变化和改进。最显著的变化是,在 Vue 3 中,v-model 可以直接用于普通 HTML 元素,而不仅仅是用于自定义组件。这意味着你可以在 input、textarea 和 select 等元素上直接使用 v-model 来实现双向数据绑定,无需再使用像 value 和 input 事件这样的属性和事件。


vue3中的v-model指令与vue2中的v-model指令有一些不同。在vue2中,v-model指令是用于在表单元素上创建双向数据绑定的指令,它可以在表单输入时更新绑定的数据,并且可以在数据改变时更新表单的值。在vue3中,v-model指令被废弃了,取而代之的是新的v-model指令的使用方式。

在vue3中,v-model指令可以用于任何组件,而不仅仅是表单元素。它是一个自定义指令,可以在组件中自定义其行为。

基本用法

v-model 可以在组件上使用以实现双向绑定。

从 Vue 3.4 开始,推荐的实现方式是使用 defineModel() 宏:

<!-- Child.vue -->
<script setup>
const model = defineModel()

function update() {
  model.value++
}
</script>

<template>
  <div>parent bound v-model is: {{ model }}</div>
</template>

父组件可以用 v-model 绑定一个值:

<!-- Parent.vue -->
<Child v-model="count" />

defineModel() 返回的值是一个 ref。它可以像其他 ref 一样被访问以及修改,不过它能起到在父组件和当前变量之间的双向绑定的作用:

  • 它的 .value 和父组件的 v-model 的值同步;
  • 当它被子组件变更了,会触发父组件绑定的值一起更新。

这意味着你也可以用 v-model 把这个 ref 绑定到一个原生 input 元素上,在提供相同的 v-model 用法的同时轻松包装原生 input 元素:

<script setup>
const model = defineModel()
</script>

<template>
  <input v-model="model" />
</template>

底层机制

defineModel 是一个便利宏。 编译器将其展开为以下内容:

  • 一个名为 modelValue 的 prop,本地 ref 的值与其同步;
  • 一个名为 update:modelValue 的事件,当本地 ref 的值发生变更时触发。

在 3.4 版本之前,你一般会按照如下的方式来实现上述相同的子组件:

<script setup>
const props = defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])
</script>

<template>
  <input
    :value="props.modelValue"
    @input="emit('update:modelValue', $event.target.value)"
  />
</template>

如你所见,这显得冗长得多。然而,这样写有助于理解其底层机制。

因为 defineModel 声明了一个 prop,你可以通过给 defineModel 传递选项,来声明底层 prop 的选项:

// 使 v-model 必填
const model = defineModel({ required: true })

// 提供一个默认值
const model = defineModel({ default: 0 })

v-model 的参数

v-model on a component can also accept an argument:

<MyComponent v-model:title="bookTitle" />

In the child component, we can support the corresponding argument by passing a string to defineModel() as its first argument:

<!-- MyComponent.vue -->
<script setup>
const title = defineModel('title')
</script>

<template>
  <input type="text" v-model="title" />
</template>

If prop options are also needed, they should be passed after the model name:

const title = defineModel('title', { required: true })

多个 v-model 绑定

利用刚才在 v-model 参数小节中学到的指定参数与事件名的技巧,我们可以在单个组件实例上创建多个 v-model 双向绑定。

组件上的每一个 v-model 都会同步不同的 prop,而无需额外的选项:

<UserName
  v-model:first-name="first"
  v-model:last-name="last"
/>
<script setup>
const firstName = defineModel('firstName')
const lastName = defineModel('lastName')
</script>

<template>
  <input type="text" v-model="firstName" />
  <input type="text" v-model="lastName" />
</template>

处理 v-model 修饰符

在学习输入绑定时,我们知道了 v-model 有一些内置的修饰符,例如 .trim.number 和 .lazy。在某些场景下,你可能想要一个自定义组件的 v-model 支持自定义的修饰符。

我们来创建一个自定义的修饰符 capitalize,它会自动将 v-model 绑定输入的字符串值第一个字母转为大写:

<MyComponent v-model.capitalize="myText" />

Modifiers added to a component v-model can be accessed in the child component by destructuring the defineModel() return value like this:

<script setup>
const [model, modifiers] = defineModel()

console.log(modifiers) // { capitalize: true }
</script>

<template>
  <input type="text" v-model="model" />
</template>

To conditionally adjust how the value should be read / written based on modifiers, we can pass get and set options to defineModel(). These two options receive the value on get / set of the model ref and should return a transformed value. This is how we can use the set option to implement the capitalize modifier:

<script setup>
const [model, modifiers] = defineModel({
  set(value) {
    if (modifiers.capitalize) {
      return value.charAt(0).toUpperCase() + value.slice(1)
    }
    return value
  }
})
</script>

<template>
  <input type="text" v-model="model" />
</template>

带参数的 v-model 修饰符

这里是另一个例子,展示了如何在使用多个不同参数的 v-model 时使用修饰符:

<UserName
  v-model:first-name.capitalize="first"
  v-model:last-name.uppercase="last"
/>
<script setup>
const [firstName, firstNameModifiers] = defineModel('firstName')
const [lastName, lastNameModifiers] = defineModel('lastName')

console.log(firstNameModifiers) // { capitalize: true }
console.log(lastNameModifiers) // { uppercase: true}
</script>

例子

1.使用v-model绑定数据:

<template>
  <input v-model="message" />
  <p>{{ message }}</p>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const message = ref('');

    return {
      message
    };
  }
}
</script>

2.使用v-model绑定复选框:

<template>
  <input type="checkbox" v-model="isChecked" />
  <p>{{ isChecked }}</p>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const isChecked = ref(false);

    return {
      isChecked
    };
  }
}
</script>

3.使用v-model绑定下拉列表:

<template>
  <select v-model="selectedOption">
    <option value="option1">Option 1</option>
    <option value="option2">Option 2</option>
    <option value="option3">Option 3</option>
  </select>
  <p>{{ selectedOption }}</p>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const selectedOption = ref('option1');

    return {
      selectedOption
    };
  }
}
</script>

4.使用v-model绑定单选按钮:

<template>
  <input type="radio" value="option1" v-model="selectedOption" /> Option 1
  <input type="radio" value="option2" v-model="selectedOption" /> Option 2
  <input type="radio" value="option3" v-model="selectedOption" /> Option 3
  <p>{{ selectedOption }}</p>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const selectedOption = ref('option1');

    return {
      selectedOption
    };
  }
}
</script>

5.使用v-model绑定多个输入框:

<template>
  <input v-model="firstName" placeholder="First Name" />
  <input v-model="lastName" placeholder="Last Name" />
  <p>{{ firstName }} {{ lastName }}</p>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const firstName = ref('');
    const lastName = ref('');

    return {
      firstName,
      lastName
    };
  }
}
</script>

6.使用v-model绑定动态输入框列表:

<template>
  <button @click="addInput">Add Input</button>
  <div v-for="(input, index) in inputs" :key="index">
    <input v-model="inputs[index]" />
    <button @click="removeInput(index)">Remove</button>
  </div>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const inputs = ref([]);

    const addInput = () => {
      inputs.value.push('');
    }

    const removeInput = (index) => {
      inputs.value.splice(index, 1);
    }

    return {
      inputs,
      addInput,
      removeInput
    };
  }
}
</script>

7.使用v-model绑定数字输入框:

<template>
  <input type="number" v-model="count" />
  <p>{{ count }}</p>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const count = ref(0);

    return {
      count
    };
  }
}
</script>

8.使用v-model绑定字符限制输入框:

<template>
  <input v-model="text" maxlength="10" />
  <p>{{ text }}</p>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const text = ref('');

    return {
      text
    };
  }
}
</script>

9.使用v-model绑定密码输入框:

<template>
  <input type="password" v-model="password" />
  <p>{{ password }}</p>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const password = ref('');

    return {
      password
    };
  }
}
</script>

10.使用v-model绑定文本区域:

<template>
  <textarea v-model="message"></textarea>
  <p>{{ message }}</p>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const message = ref('');

    return {
      message
    };
  }
}
</script>

总结:Vue 3 中的 v-model 指令与 Vue 2 中的 v-model 相比有一些变化和改进。最显著的变化是,在 Vue 3 中,v-model 可以直接用于普通 HTML 元素,而不仅仅是用于自定义组件。这意味着你可以在 input、textarea 和 select 等元素上直接使用 v-model 来实现双向数据绑定,无需再使用像 value 和 input 事件这样的属性和事件。

此外,Vue 3 中的 v-model 还可以自定义修饰符。修饰符是一种特殊标记,可以在 v-model 绑定上使用,以更改其行为。例如,你可以使用 .lazy 修饰符来实现延迟更新,从而仅在用户完成输入后才更新绑定的值。

另一个变化是,在 Vue 3 中,v-model 生成的属性和事件名称可以通过 setup() 函数中的 `v-model` 选项进行自定义。这意味着你可以使用不同的名称来指定生成的属性和事件,以适应不同的使用场景。

总之,Vue 3 中的 v-model 指令增加了对普通 HTML 元素的支持,并引入了自定义修饰符和属性/事件名称定制的功能,使双向数据绑定更加灵活和易用。

Logo

前往低代码交流专区

更多推荐