vue v model

  • 2021-08-09 07:03:46
  • OfStack

1. v-model principle

v-model in vue is a grammar sugar, and the so-called grammar sugar is the function produced by packaging other basic functions twice. Simply put, v-model itself is the parent component's encapsulation of child component state and state change events. Its realization principle is divided into two parts:

Set the state of subcomponents through props
Change the state of the parent component by listening for events emitted by the child component, thus affecting the props value of the child component
Through the above two parts, the effect of binding the state of the parent component and the state of the child component is realized.

1.1 demo

v-model Usage Sample


<!DOCTYPE html>
<html>
 <head>
 <meta charset="utf-8" />
 <title>v-model Example </title>
 <script type="text/javascript" src="vue.js"></script>
 </head>

 <body>
 <div id="app">
 <div> Here is the state of the parent component :</div>
 <div style="margin-bottom: 15px;">{{content}}</div>
 <Child v-model="content"></Child>
 </div>

 <template id="input">
 <div>
 <div> This is the input area of the subcomponent :</div>
 <input :value="value" @input="contentChange" />
 </div>
 </template>

 <script type="text/javascript">
 var Child = {
 template: "#input",
 props: {
 value: {
 type: String,
 required: true
 }
 },
 methods: {
 contentChange(value){
 this.$emit("input", value.target.value);
 }
 }
 };

 var vueInstance = new Vue({
 el: "#app",
 components: {Child},
 data: {
 content: ""
 }
 })
 </script>
 </body>
</html>

Open the above html page in the browser, and you can see the real-time effect: the input content in the input box in the subcomponent can be displayed in the parent component area in real time, thus achieving the effect of real-time binding between the state in the subcomponent and the state of the parent component.

2. Modify the default v-model listens for events and set the name of prop

The v-model instruction defaults to setting the name of prop on the child component, which is value. By default, it listens for input events on the child component. On demo above, if we modify the name of events issued in the contentChange function of the child component, the input of the child component cannot be obtained in real time in the parent component.

Vue provides the ability to modify these two parameter names by defining model attributes on subcomponents, but this ability needs to be used above version 2.2, as shown in the following demo:

2.1 demo


<!DOCTYPE html>
<html>
 <head>
 <meta charset="utf-8" />
 <title>v-model Example </title>
 <script type="text/javascript" src="vue.js"></script>
 </head>

 <body>
 <div id="app">
 <div> Here is the state of the parent component :</div>
 <div style="margin-bottom: 15px;">{{content}}</div>
 <Child v-model="content"></Child>
 </div>

 <template id="input">
 <div>
 <div> This is the input area of the subcomponent :</div>
 <input :value="content" @input="contentChange" />
 </div>
 </template>

 <script type="text/javascript">
 var Child = {
 template: "#input",
 model: {
 prop: "content",
 event: "contentChanged"
 },
 props: {
 content: {
 type: String,
 required: true
 }
 },
 methods: {
 contentChange(value){
 this.$emit("contentChanged", value.target.value);
 }
 }
 };

 var vueInstance = new Vue({
 el: "#app",
 components: {Child},
 data: {
 content: ""
 }
 })
 </script>
 </body>
</html>

3. Analysis of v-model instruction processing in Vue

Based on Vue version 2.0, analyze our process of writing v-model attributes on tags to vue components to implement responses.

3.1 Parsing section

3.1. 1 When HTML is parsed to AST, the attributes of tags in HTML are parsed


function processAttrs(el){
 ...
 name = name.replace(dirRE, '')
 // parse arg
 const argMatch = name.match(argRE)
 if (argMatch && (arg = argMatch[1])) {
 name = name.slice(0, -(arg.length + 1))
 }
 addDirective(el, name, value, arg, modifiers)
 ...
}

Extract the name of the instruction, name is model for v-model, and add it to the instruction of the instance

3.1. 2 Add instruction-related content to the instance instruction


export function addDirective (
 el: ASTElement,
 name: string,
 value: string,
 arg: ?string,
 modifiers: ?{ [key: string]: true }
) {
 (el.directives || (el.directives = [])).push({ name, value, arg, modifiers })
}

The corresponding instruction is added to the instruction attribute of the instance, so that the conversion from the attribute on html to the instruction format on Vue instance is realized

3.2 Instruction Setting Section

After html is parsed to AST, the v-model related values set by us will be found on the directives attribute corresponding to the instance, including the parameter value value, and name is model

3.2. 1 Invoke the constructor of the instruction


function genDirectives (el: ASTElement): string | void {
 const dirs = el.directives
 if (!dirs) return
 let res = 'directives:['
 let hasRuntime = false
 let i, l, dir, needRuntime
 for (i = 0, l = dirs.length; i < l; i++) {
 dir = dirs[i]
 needRuntime = true
 const gen = platformDirectives[dir.name] || baseDirectives[dir.name]
 if (gen) {
 // compile-time directive that manipulates AST.
 // returns true if it also needs a runtime counterpart.
 needRuntime = !!gen(el, dir, warn)
 }
 ...
}

In the constructor of v-model instruction, different creation functions will be created according to the type of tag. If we need to add attributes to sub-components for custom instruction, we also need to operate in this function

3.2. 2 v-model instruction construction process under normal tag


function genDefaultModel 
 el: ASTElement,
 value: string,
 modifiers: ?Object
): ?boolean {
 ...
 addProp(el, 'value', isNative ? `_s(${value})` : `(${value})`)
 addHandler(el, event, code, null, true)
 ...
}
addProp Sets an prop named value on el and sets its value addHandler sets event handlers on el

3.3 Instruction response change part

3.3. 1 Hook function for createPatchFunction 1 processing instructions
The createPatchFunction function returns an patch function, and during patch processing, the hook function of the instruction is called, including:

bind inserted update componentUpdated unbind

4. Summary

4.1 Compilation process

Parse the set instruction from html Instructions are set to AST through the gen* function Call the constructor of the instruction to set what the instruction needs to do at compile time

4.2 Initialization Procedures

In patch function, the hook function of system 1 is called to trigger the hook function of instruction, and the corresponding functions are realized

The above is the detailed explanation of vue v-model. For more information about vue v-model, please pay attention to other related articles on this site!


Related articles: