Component v-model
basic usage
-
Data two-way binding
-
His principle is to pass a property named modelValue and register a custom event named @update:modelValue. In the subcomponent, you need to receive the modelValue property in defineProps and declare defineEmits.
-
If you do not do anything, the default binding is the modelValue attribute and the registration @update:modelValue event, but it can also be modified, you can change the name through v-model:title
-
reflected in the code
-
// 父组件 <template> <div> <!-- <VModel v-model="title"></VModel> --> <!-- 修改绑定的默认名称 --> <VModel v-model:title="title"></VModel> </div> </template> <script setup> import { ref } from 'vue' import VModel from './components/zujianup/02-组件v-model.vue' const title = ref('爱你孤生走暗巷') </script> // 子组件 <template> <div> <!-- <h1>子组件传过来的值为:{ { prop.modelValue }}</h1> --> <h1>子组件传过来的值为:{ { prop.title }}</h1> <button @click="changeTitle">更改父组件传过来的值</button> </div> </template> <script setup> // const prop = defineProps(['modelValue']) // const emit = defineEmits(['update:modelValue']) const prop = defineProps(['title']) const emit = defineEmits(['update:title']) const changeTitle = () => { emit('update:modelValue', '爱你不跪的模样') } </script>
The difference with v-model in vue2
- The v-moel in vue2 can only be bound once on the component, and multiple bindings need to use .sync syntactic sugar
- The v-model in vue3 is more similar to .sync, and can modify the name, so it can bind multiple on a component tag, and multiple bound v-models can be distinguished by modifying the name
Modifiers for custom v-model
-
v-model has some custom events, but some modifiers need to be customized in some scenarios
-
e.g. capitalize
-
// 子组件 <script setup> const props = defineProps({ modelValue: String, modelModifiers: { default: () => ({}) } // 在defineProps通过modelModifiers声明 }) const emit = defineEmits(['update:modelValue']) function emitValue(e) { let value = e.target.value // 如果用了这个自定义修饰符,则执行相应的逻辑 if (props.modelModifiers.capitalize) { // 首字母大写的逻辑 value = value.charAt(0).toUpperCase() + value.slice(1) } emit('update:modelValue', value) } </script> <template> <input type="text" :value="modelValue" @input="emitValue" /> </template> // 父组件 <template> <div> <!-- v-model后面跟自定义修饰符 --> <Component3 v-model.capitalize="myText" /> </div> </template> <script setup> import { ref } from 'vue' import Component3 from './components/zujianup/Component3.vue' const myText = ref('abcd') </script>