Use v-Models on components

1, the introduction of

The purpose of using V-Models on components is also for bidirectional binding, which is especially useful when we want to implement bidirectional data binding when we encapsulate higher-order form components.

2, use,

<! Child v-model="message" @update:model-value="updateMessage" ></child> </div> </template> <script setup> import { ref } from "@vue/reactivity"; import Child from "./Child.vue"; let message = ref("Hello World Vue3"); const updateMessage = (val) => { message.value = val } </script> <! <div> <input type="text" v-model="propsMessage"> </div> </template> <script setup> import { computed } from "@vue/reactivity" const emmits = defineEmits(['update:modelValue']) let props = defineProps({ modelValue: String }) const propsMessage = computed({ get: () => { return props.modelValue }, set: (val) => { emmits('update:modelValue', val) } }) </script>Copy the code
  • There are two things to note in the above code. 1. Actually adopt< component name V-model ="property"></ component name >This is actually a syntactic sugar notation, which is equivalent to< component name :model-value="property" @update: model-Value ="emitEvent">. 1. In the above code we use the default writing, i.ev-model="property"When the child component props accepts the value, it is converted to a real property:model-value="property"The value defined in props ismodelValue.

The default method is update:modelValue. Can you change this parameter? Yes.

3, custom event name method pass

<! Parent component --> <template> <div> <child V-model :custom="message" @update:custom="updateCustom" ></child> <h1>{{message }}</h1> </div> </template> <script setup> import { ref } from "@vue/reactivity"; import Child from "./Child.vue"; let message = ref("Hello World Vue3"); const updateCustom = (val) => { message.value = val } </script> <! <div> <input type="text" v-model="propsMessage"> </div> </template> <script setup> import { computed } from "@vue/reactivity" const emmits = defineEmits(['update:modelValue']) let props = defineProps({ custom: String }) const propsMessage = computed({ get: () => { return props.custom }, set: (val) => { emmits('update:custom', val) } }) </script>Copy the code

In the third way, we can see that the custom pass name can be modified by using v-mode:[variable] to modify the default modelValue.

4. Source code interpretation

I found the source code for this section. When the virtual DOM node is defined, the V-Model binding component is transformed into the virtual DOM node using transformModel method. When defining the event name, there is the following source code.

  const eventName = arg
    ? isStaticExp(arg)
      ? `onUpdate:${arg.content}`
      : createCompoundExpression(['"onUpdate:" + ', arg])
    : `onUpdate:modelValue`
Copy the code