学习优先度:★★★★☆
难易度:★★★☆☆
Vue 3 为 v-model 引入了一种新的参数语法,允许更灵活、更明确地绑定组件属性。
在 Vue 2 中,v-model 主要用于绑定组件的值和监听输入事件。Vue 3 通过新的语法增强了这一功能,让您可以绑定到不同的属性和事件。
【代码示例】
// Vue 2 v-model usage
// This will bind the input to the 'message' data property
Vue.component('custom-input', {
props: ['value'],
template: `
<input
:value="value"
@input="$emit('input', $event.target.value)"
\>
`
});
new Vue({
el: '#app',
data: {
message: 'Hello Vue 2!'
}
});
// Vue 3 v-model usage
// This binds the input to the 'modelValue' property and uses 'update:modelValue' event
import { createApp } from 'vue';
const CustomInput = {
props: ['modelValue'],
template: `
<input
:value="modelValue"
@input="$emit('update:modelValue', $event.target.value)"
\>
`
};
createApp({
components: {
CustomInput
},
data() {
return {
message: 'Hello Vue 3!'
};
},
template: `
<div>
<custom-input v-model="message"></custom-input>
<p>{{ message }}</p>
</div>
`
}).mount('#app');
【执行结果】
应用程序会显示一个绑定到消息数据属性的输入字段,并且段落标签会随着您的输入而更新。
在 Vue 3 中,v-model 已被通用化,允许更明确的绑定和事件命名。新语法允许绑定到 value 以外的属性,并监听输入以外的事件。这是通过使用 modelValue 作为默认属性和 update:modelValue 作为默认事件来实现的。您还可以将多个 v-model 指令绑定到一个组件的不同属性上。
【补充】
这一更改提高了 Vue 应用程序中数据绑定的灵活性和清晰度,使管理复杂表单和自定义输入组件变得更加容易。明确的命名约定有助于避免冲突并提高代码的可读性。