It will take about 25 minutes to read the complete text.

I divide a beginner’s learning of new technology into 3 large stages and 8 small stages, which are:

Stage 1: Introduction and familiarity

  1. Use it first: Learn Vue3 from the perspective of a Vue beginner who has worked for many years: Getting to know Vue components
  2. Be familiar with the API:At this stage

Phase two: Use and output

  1. Work on an actual project
  2. Writing extension plug-ins
  3. Output summary article

Stage three: Principles and reinvention

  1. Understand the overall architecture and design
  2. Analysis of the source code
  3. Make a mini version

In the last article, we created a Vue3 project and got it running successfully.

The main goal of this step is to get an emotional impression of the new technology. By the end of this step, we will know:

  1. What this new technology does
  2. What are its basic structures (basic concepts)
  3. How does it work

From the previous article:

Learn Vue3 from the perspective of a Vue beginner who has worked for many years: first introduction to Vue components

We have largely accomplished the above objectives:

  1. Learn that Vue3 is a progressive JavaScript framework for building UI layers
  2. Its basic structure is the Vue component, the Vue component consists of template/script/style three parts
  3. Get Vue3 up and running with Vite Project and experience a very smooth hot Update (HMR) for Vite

In the first stage we just need to get the emotional impression, run it, experience it, change this, change that, and see what happens. Open this up, see what’s inside, and then cover it back up. If you’re interested in that, go to the website and take a look at the API, or try it out for yourself.

The second phase requires a broader understanding of the new technology, the big picture, and keeping in mind the most frequently used apis. According to the 80-20 rule, 20% of the API will cover 80% of the project scenarios, so the most important task is to get familiar with the API and memorize the 20% of the high-frequency apis.

This is where we need to look at Vue3’s official documentation: vue3js.cn/docs/zh/gui…

1. Read the document with thought

When a document writer writes a document, he or she will write the reader as if he or she were a “fool.” The result is a clearer, more complete document that is easier for the reader to understand.

But in fact, readers are not “fools” without any foundation. Different readers have different experiences and backgrounds, and their acceptance and understanding of documents are also different.

Therefore, when we look at the documents, we don’t necessarily have to read them in full order, but we should combine our actual situation to read them in a targeted and purposeful way.

The document is only a reference. There are many ways for us to learn new technologies, and reading the document is only one way. Therefore, when reading the document, we must read it with thinking and questions, rather than blindly from beginning to end.

In the last phase we learned that the Vue component is divided into three parts:

  • template
  • script
  • style

This is the way to look at the documentation.

First look at the basic section of the document:

Most of this is in the Template section (red box), and some script content (blue box).

In the first stage, we already have an intuitive impression of template:

  • The Vue template syntax can be used in the template to dynamically render data
  • Text interpolation(wrapped in double braces) is a very basic template syntax
  • @clickIs the syntax for Vue event binding

We learned three keywords: template syntax, text interpolation, and event binding.

So the first step in looking at the documentation should be to delve into what these concepts are. Then, through the concept of these single points, the entire template syntax line is strung.

The template syntax and text interpolation are documented at vue3js.cn/docs/zh/gui…

The event binding document is at: vue3js.cn/docs/zh/gui…

If you want to go straight to the summary, you can skip to the following sections: 6 Summary

2 Overview of template syntax

The documentation for template syntax is really about two things: interpolation and instructions.

We have a good understanding of interpolation, and we know:

Text interpolation is the binding of a Vue component variable to the template, and the value of the variable is eventually rendered into the template.

<h1>{{ msg }}</h1>

<HelloWorld msg="Hello Vue 3 + TypeScript + Vite" />
Copy the code

The final render is:

<h1>Hello Vue 3 + TypeScript + Vite</h1>
Copy the code

By reading a document, our goal is to connect the dots, from line to line, from line to surface.

Text interpolation is just a point. What is a line?

All interpolation types are lines, the entire template syntax is lines, and the principle of template compilation is lines.

Let’s string them one by one.

3 the interpolation

As we can see from the documentation, in addition to text interpolation, there are

  • HTML interpolation
  • Attribute interpolation
  • JavaScript expression support

3.1 HTML interpolation

The document gives a very good example of HTML interpolation, which is very clear:

<p>Using mustaches: {{ rawHtml }}</p>

<p>Using v-html directive: <span v-html="rawHtml"></span></p>
Copy the code
rawHtml: '<span style="color: red">This should be red.</span>'
Copy the code

The same HTML string text, through text interpolation, will display the HTML string text directly; HTML interpolation renders the HTML string (in this case, a red text).

Here we use a Vue directive: V-HTML.

This is the second Vue instruction we have been exposed to. A V-once instruction also appeared in the previous text interpolation, which is used for one-time interpolation.

So we don’t have to go into the details of what the Vue directive is, we’ll get into that later, but just know, right

  • It is av-At the beginning of
  • A “command” used on an HTML element or a Vue component element
  • When this “command” element is used, its performance or behavior changes

That’s all you need to know.

3.2 Attribute interpolation

In addition to inserting variables into elements, you can also insert variables into elements’ attributes, such as id/disabled/title/ SRC.

Interpolating properties requires the aid of another Vue directive: V-bind.

<div v-bind:id="dynamicId"></div>
Copy the code
dynamicId: 'name1'
Copy the code

The final render is:

<div id="name1"></div>
Copy the code

This is the third instruction, and there are many more Vue built-in instructions to follow.

These instructions are used very frequently in practice, and they all need to be remembered as part of the 20% API.

This v-bind:id directive is different from the previous v-once and V-HTML directives. This v-bind directive takes an argument. In this case, the argument is ID, indicating that the attribute id needs to be bound.

The v-bind directive is so common that Vue gives it a shortened form. For example, v-bind:id can be written as: ID:

<div v-bind:id="dynamicId"></div>< = ><div :id="dynamicId"></div>
Copy the code

3.3 Using JavaScript expressions

In the previous interpolation, we only bind a variable, but we can also bind a JavaScript expression, such as:

<h1>{{ hasMsg ? msg : 'Hello World' }}</h1>
Copy the code

The above text interpolation binds a ternary operator with two variables and a string:

  • When hasMsg is true, the value of MSG is actually bound
  • When hasMsg is false, bind the string ‘Hello World’

Property interpolation can also bind expressions:

<div v-bind:id="'list-' + id"></div>
Copy the code

The above property interpolation binds a string concatenation expression, which actually binds the string ‘list-‘ to the value of the variable ID after concatenation.

So we connect the interpolating lines.

Let’s review:

  • Interpolation is binding variables of a component instance to the DOM
  • A total ofText interpolation,HTML interpolation,Attribute interpolationThree types of interpolation
  • Interpolation supports JavaScript expressions in addition to variables
  • Learn that the Vue directive is a “command” applied to an element that affects its performance and behavior
  • Learned three commonly used Vue instructions:v-once/v-html/v-bind(V-bind is a parameter instruction)

4 orders

In addition to the interpolation line, there is an instruction line on the template syntax line.

We have already had a preliminary understanding of instructions, and learned three simple instructions, and also understand that instructions can actually take parameters.

These are all isolated points, and by reading the document, we can complete the known outliers and make a line.

Directives are special Directives with a V-prefix that:

When the value of an expression changes, its knock-on effects are applied to the DOM in response.

An example of the V-if directive is described in the documentation:

<p v-if="seen">Now you see me</p>
Copy the code

If the seen variable is true, then the final render is:

<p> Now you see me </p>Copy the code

If seen as false, the P element is not rendered:

<! --v-if-->Copy the code

V-if is the fourth Vue built-in instruction we learned, and is also very common.

Through the document we know that in addition to the general instructions and parameter instructions, there are:

  • Dynamic parameter instruction
  • An instruction with a modifier

4.1 Dynamic parameter instruction

Parameter instructions were mentioned earlier when we introduced interpolating properties:

<div v-bind:id="dynamicId"></div>
Copy the code

V-bind is a typical parameter directive that can be used to update HTML attributes responsively, such as the id attribute in the above example.

Another parameter directive is v-ON, which is used for event binding. For example, if you want to bind a button to a click event:

<button type="button" v-on:click="confirm">determine</button>
Copy the code

Click after v-ON is the parameter to this directive, which means that the click event is bound.

You can also write a JavaScript expression that makes it a dynamic argument, such as:

<div v-bind:[attributeName] ="dynamicValue">Test dynamic parameter instruction</div>
Copy the code

When attributeName is ID, it binds to the attribute ID, and when attributeName is title, it binds to the attribute title, so it’s called: dynamic parameter instruction.

V-on directives can also take dynamic parameters, such as:

<a v-on:[eventName] ="doSomething">Test the dynamic parameters of the V-ON instruction</a>
Copy the code

When eventName is click, it binds to the click event. When eventName is focus, the focused event is bound.

4.2 Instructions with modifiers

Modifier (modifier) is a half – Angle period. Specified special suffix used to indicate that an instruction should be bound in a particular way.

In addition to parameters, v-ON directives can also carry modifiers (such as the.prevent modifier).

<a v-on:click.prevent="confirm" href="https://devui.design/">Hyperlinks with the prevent modifier</a>
Copy the code

The. Prevent modifier will call event.preventDefault() after the event is triggered to prevent the default jump action of the hyperlink, so the confirm method will only be executed after the above hyperlink is clicked, not jump.

If you do not use the.prevent modifier, the default jump behavior of the hyperlink will be performed after the confirm event is executed and the hyperlink will be redirected to https://devui.design/ :

<a v-on:click="confirm" href="https://devui.design/">Normal hyperlink</a>
Copy the code

Note that:

The Vue directive can have only one argument, while modifiers can have multiple

Most of Vue’s modifiers currently exist in the V-ON directive.

V-on, the fifth Vue built-in instruction we learned, is used to bind events. It is so common that Vue, like v-bind, provides specific abbreviations for v-on directives. For example, v-on:click can be abbreviated to @click:

<button type="button" v-on:click="confirm">determine</button>< = ><button type="button" @click="confirm">determine</button>
Copy the code

A review of the Vue built-in directives we’ve learned so far:

  1. v-once: interpolate once, and cache the value, immutable
  2. v-html: HTML interpolation, used to render HTML content, prone to XSS attacks, use with caution
  3. v-bindAttribute binding, used to update HTML attributes responsively, with parameters/dynamic parameters,v-bind:attributeNameCan be abbreviated as:attributeName
  4. v-if: very common and used to dynamically insert/remove elements and components, which actually removes the element from the DOM tree
  5. v-on: commonly used, used for event binding, can take parameters/dynamic parameters, can take modifiers,v-on:eventNameCan be abbreviated as@eventName

So we’ve basically strung the instruction line together.

At this point, the template syntax lines are basically strung together, but there are a few things missing:

  1. Instruction is a very key concept in Vue with a lot of content. In fact, the basic part of Vue3 document is mostly about some built-in instructions of Vue, so the instruction line is very long. The instruction line we have now is incomplete, and will continue to extend in the futureCommand line
  2. Among the many built-in instructions,v-onEvent binding is a very basic and important one, and has been mentioned many times before, so it is included in this article
  3. There is another concept in template syntax that is missingbasisInside, but inFurther componentsIn the file ofThe template referenceIt’s pretty simple, it’s not much, but I think it’s also part of the template syntax line, so I’ll put it in there, okay

Thank you so much for making it this far. There are only 5 minutes left to read, so relax with a glass of water 😋

4.3 Event Binding

Event binding was actually seen in the first article:

<button type="button" @click="count++">count is: {{ count }}</button>
Copy the code

But there was a sense of awareness in a single point manner.

We’ve seen v-ON event binding many times before when we introduced dynamic parameter directives and modifiers, and now we know that it’s part of the instruction line, which is part of the long line of template syntax, so the dots are strung together.

If we only remember a few points at a time when learning, without a line, it is difficult to make associations of knowledge, and scattered knowledge points are easy to forget.

Once the dots are strung together, and the threads are woven into surfaces, we can see the new technology from a global perspective, from a connection perspective, easily remember, and flexibly use the new technology.

Event binding in Vue is done through the V-ON directive, and the V-ON :eventName directive is abbreviated to @eventName.

We already know how to bind events:

<button type="button" @click="count++">count is: {{ count }}</button>
Copy the code

The count variable increments by 1 each time the button is clicked.

Count++ in the example above is an expression. From reading the official documentation, we know that in addition to writing an expression, we can also write:

  • Event handling methods
  • Inline methods in the processor
  • Multievent handler
  • Event modifier
  • Key modifier
  • System modifier key

4.3.1 Event Handlers

An event handler binds an event to a method name.

<button type="button" @click="add">count is: {{ count }}</button>
Copy the code
setup() {
  const count = ref(0)

  const add = () = > {
    count.value++
  }

  return {
    count,
    add,
  }
}
Copy the code

In addition to binding method names, methods can also be executed directly (inline handlers) :

<button type="button" @click="add()">count is: {{ count }}</button>
Copy the code

Instead of executing a single method, you can execute multiple methods at once, separated by commas:

<button type="button" @click="add(),double()">count is: {{ count }}</button>
Copy the code
setup() {
  const count = ref(0)

  const add = () = > {
    count.value++
  }

  const double = () = > {
    count.value = count.value * count.value
  }

  return {
    count,
    add,
    double,
  }
}
Copy the code

4.3.2 Event modifiers

Event modifiers, which we also briefly looked at when we talked about instructions with modifiers, are denoted by the suffix of an instruction that begins with a dot.

Here are some common event modifiers:

  • .stopPrevent event propagation
  • .preventPrevents default event behavior
  • .captureUse event capture mode
  • .selfTrigger only when the point is in itself (not when the elements inside the point are inside)
  • .onceThe event is triggered only once
  • .passiveThe default behavior of the scroll event (i.e., the scroll behavior) is triggered immediately, without waitingonScrollcomplete

The first four are mostly for click events, and I’ve made a few demos to help you understand what they mean.

<div @click="containerClick" style="border: solid 1px red">
  Container
  <div @click="outClick" style="border: solid 1px green; margin: 20px; padding: 20px;">
    Button wrapper
    <button type="button" @click="add">Add</button>
  </div>
</div>
Copy the code
setup() {
  const containerClick = () = > {
    console.log('containerClick')}const outClick = () = > {
    console.log('outClick')}const add = () = > {
    console.log('add')}return {
    containerClick,
    outClick,
    add,
  }
}
Copy the code

There are three elements and three clicks from the outside to the inside:

  • The outermost Container element (Container red circle)
  • The outer element of the Button (Button wrapper green circle)
  • Button element (Button blue circle)

By default, events follow a bubbling propagation pattern (from the inside out).

When we click on the button elements, they are printed in turn:

add
outClick
containerClick
Copy the code

Clicking on the outer elements of the button will print them in turn:

outClick
containerClick
Copy the code

The. Stop modifier starts with the. Stop modifier. The. Stop modifier starts with the. Stop modifier.

Stop the modifier

We add a. Stop modifier to the button element, which will prevent the event from propagating upward.

<button type="button" @click.stop="add">Add</button>
Copy the code

Only the following will be printed:

add
Copy the code

The self modifier

If you add a. Self modifier to the outer element of a button, it will trigger only when the element is actually clicked, not when the button inside is clicked.

<div @click.self="outClick" style="border: solid 1px green; margin: 20px; padding: 20px;">
  Button wrapper
  <button type="button" @click="add">Add</button>
</div>
Copy the code

At this point, if you click the button, it will only print:

add
Copy the code

If you click on the outer element of the button, it will print:

outClick
containerClick
Copy the code

The capture modifier

Adding the capture modifier to the click event of an element means that the event propagation of that element follows an out-and-in capture pattern, affecting only the event propagation pattern of that element.

Add the. Capture modifier to the element outside the button:

<div @click.capture="outClick" style="border: solid 1px green; margin: 20px; padding: 20px;">
  Button wrapper
  <button type="button" @click="add">Add</button>
</div>
Copy the code

Clicking the button element at this point will print:

outClick
add
containerClick
Copy the code

There are two other event modifiers that are useful:

  • Key modifiers enter/TAB/delete/space, etc
  • System modifiers CTRL/Alt/Shift/Meta etc

There are many modifiers involved, and it is also easy to understand. You can read the official website document by yourself if you are interested.

Key modifier

System modifier key

Add the event handling line, and the instruction line becomes more complete.

5 Template Reference

For the template syntax line, there is one template reference left.

Look at the official documentation for how to interpret template references:

Despite the existence of prop and events, sometimes you may still need direct access to child components in JavaScript. To do this, you can use the REF Attribute to specify a reference ID for a child component or HTML element.

So a template reference is really about getting a specific element in the template and manipulating it. There are only two types of elements in the template:

  • Native HTML elements
  • The component element

Corresponds to two template references.

5.1 HTML element references

The HTML element reference gets the DOM element.

We add a ref attribute to the img tag and bind the reference to the IMG tag, imgRef.

<img alt="Logo" src="./assets/logo.png" ref="imgRef" />
<br />
<button type="button" @click="changeImg">Change img src</button>
Copy the code
setup() {
  const imgRef = ref(null)

  const changeImg = () = > {
    imgRef.value.src = 'src/assets/devui.png'
    imgRef.value.width = 200
  }

  return {
    imgRef,
    changeImg,
  }
}
Copy the code

5.2 Child Component references

A child component reference gets a child component instance.

For example, 🌰

<HelloWorld ref="helloWorldRef" msg="Hello everyone! I'm learning Vue 3 + TypeScript + Vite" />
<button type="button" @click="add">Add</button>
Copy the code
setup: () = > {
  const helloWorldRef = ref(null)

  const add = () = > {
    // After obtaining the reference to the child component, we can obtain the variables and methods of the component instance
    helloWorldRef.value.add()
    
    // You can also directly modify the count variable of the child component instance
    // helloWorldRef.value.count++
  }

  return { 
    helloWorldRef,
    add,
  }
}
Copy the code

hello-world.vue

<p>{{ count }}</p>
Copy the code
setup: () = > {
  const count = ref(0)

  // This method is an instance method of the component and can be called by template reference
  const add = () = > {
    count.value++
  }

  return { 
    count,
    add,
  }
}
Copy the code

At this point, the entire template syntax line is fully strung.

6 summary

Finally, use this template syntax line as a summary of this article.

That’s the end of this article. Here’s an introduction to the Vue DevUI open source project. If you’re interested, read on.


Vue DevUI is under development at 🔥. Welcome to join us and build a Vue open source component library based on DevUI design concept.

Here is the source code for the project:

Gitee.com/devui/vue-d…

Participate in the contribution can be added to the small assistant wechat: Devui-official, pull you into the Vue Devui core members group ~ 😋😋

Welcome to our DevUI component library and light up our little star 🌟 :

Github.com/devcloudfe/…

Also welcome to use DevUI newly released DevUI Admin system, out of the box, 10 minutes to build a beautiful atmosphere of the background management system!

Once again: DevUI Admin 2.0 is coming!

DevUI Admin 2.0 will also be released on The 17th of this month, providing a magical piece of dark technology, let’s wait and see!

Reference:

Vue3 Chinese document – Template syntax