Why this article?

Now that it’s 2021 and Vue3 has been released, what’s the point of writing this article that’s everywhere on the web? In fact, I have been thinking about this question before WRITING, and finally I come to the following reasons:

  • 1. I have done some projects with VUE. Although many functions can be realized, I always feel that it is too difficult to form a knowledge system
  • 2. Most of the daily development is carried out around the business, without a careful taste of the framework document, resulting in some things may be blurred after a long time
  • 3. It is also essential to learn Vue3 so well
  • 4. As the saying goes, review the past and learn something new. Although the basic things may seem simple, I think there will be unexpected harvest if I output them through my own ideas and review them for a long time.

Based on the above points, I decided to write a few combined with Vue documents to expand some articles, mainly to do knowledge combing, form a system, by the way polish the composition level, why not?

Mind mapping

Before starting any paragraph, I expect to have a mind map to illustrate the context of the article, which is not only conducive to the writing of the article, but also conducive to memory.

To the body

Before the beginning of the text, it is necessary to explain that every word in the article is written by me one by one. It is inevitable that there will be omissions or mistakes. I also request your understanding and hope that the comment area will be criticized and pointed out. This article mainly introduces the template syntax related, so it will not involve too much js logic.

Interpolation expression

The content part of a native HTML element, if you want to represent it as a variable, might need to be set dynamically by js syntax, but in Vue you don’t. You just declare your data in the display and use the variable syntax with double curly braces, and the content of the tag part will change in the future as the data changes

  • v-once

Perform the interpolation once and for all. When the data changes, the contents of the interpolation are not updated

  • v-html

The default HTML native text cannot be represented by interpolation, so using V-HTML allows the browser to display parsed HTML

<div id="app">
    <h1>{{message}}</h1>
    <h2 v-once>{{message}}</h2>
    <p v-html="rawhtml"></p>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script>
    var app = new Vue({
        el:'#app'.data: {message:'hello vue'.rawhtml:'<h3> this is html </h3>'}})</script>
Copy the code

Element attributes (that is, attribute bindings)

HTML native tags provide many standard attributes to use, such as the title attribute. In VUE, you can dynamically change the value of an attribute to a variable or expression.

<div id="app">
    <h1 v-bind:title="title">hello vue</h1>
    <h1 :title="title + '!!!' ">hello vue</h1>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script>
    var app = new Vue({
        el:'#app'.data: {title:'this is h1 title attr'}})</script>
Copy the code

Class and style

When writing templates, it is common to add class names or inline styles to elements. These two attributes as elements also support dynamic binding of a variable or expression, but Vue has enhanced this

  • class

    1. Object syntax

    When the value of the object is Truthy, the element is bound to the class corresponding to the key value. For example, red and yellow are bound to the class

    < p: class = {" red: true, blue: false, yellow: 1} "> I am a paragraph < / p >Copy the code

    2. Array syntax

    Array syntax is all about binding values to array elements, which can be strings, variables, or expressions

    3. Use it on custom components

    When applied to the use of a custom component, this class is applied to the outermost element of the component template

  • style

    Sytle also supports object syntax and array syntax. Object syntax is an object that you should write like CSS in jQuery, and array syntax is an array that can be a collection of previous object syntax. Such as:

<div id="app">

        <p :style="styleObj">Look at the style object syntax for paragraphs</p>
        <p :style="[ styleObj1,styleObj2]">Look at the style array syntax for paragraphs</p>
        

    </div>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
    <script>
        var app = new Vue({
            el:'#app'.data: {styleObj: {fontSize:'40px'.color:'red'
                },
                styleObj1: {fontSize:'20px'.color:'green'
                },
                styleObj2: {fontWeight:'bold'.backgroundColor:'red'}}})</script>
Copy the code

Evaluate properties VS listeners

  • Calculate attribute

Sometimes, an interpolation or a property binding depends on multiple values or complex conditions, which can get confusing if you write a lot of expressions in a template. I’ve seen one before that writes a lot of conditional statements at once, and writes them directly inside the line.

  • The listener

Sometimes you need to listen for property changes to perform operations, such as network requests, and you need to write a listener to handle that


    <div id="app">
      <p>{{title}}</p>
      <p>{{info.time}}</p>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
    <script>
      var app = new Vue({
        el: "#app".data: {
          city: "wuhan".age: 16.sex: "Female".info: {time:60}},computed: {title:function(val){
                if(this.city === 'wuhan' && this.age  === 16 && this.sex === 'woman') {return 'Wuhan Young Girl'
                }else{
                    return 'Wuhan Tough Woman'}}},mounted:function(){
            setInterval(() = > {
                this.info.time--;
            }, 1000);
        },
        watch: {info: {handler:function(val,oldval){
                    console.log(val,oldval);
                    // todo something
                },
                deep:true.immediate: true}}});</script>
Copy the code

The difference between the two:

  • The calculated property is cacheable and the calculated value will not be repeated if it does not change
  • Listeners are suitable for asynchronous or expensive operations

Conditions apply colours to a drawing

  • V-if V-else V-else if can implement everyday conditional rendering
<div v-if="type === 'A'">
  A
</div>
<div v-else-if="type === 'B'">
  B
</div>
<div v-else-if="type === 'C'">
  C
</div>
<div v-else>
  Not A/B/C
</div>
Copy the code
  • To handle conditional rendering issues, Vue does not foolishly re-render everything, but renders as efficiently as possible, for example:
<template v-if="loginType === 'username'">
  <label>Username</label>
  <input placeholder="Enter your username">
</template>
<template v-else>
  <label>Email</label>
  <input placeholder="Enter your email address">
</template>
Copy the code

By default, vUE will reuse this form entry when the login type changes. Sometimes you may want to switch the login method and the form entry will need to be independently re-rendered. In this case, you just need to set a different key for this form entry

  • v-show & v-if

V-show renders regardless of whether the condition is true or false, whereas V-if renders elements only if the condition is true. So in general, if the template code segment is frequently switched, you might want to use V-show, because v-if will frequently destroy and rebuild event listeners and subcomponents appropriately within the conditional block.

  • v-for & v-if

When v-if is used with V-for, v-for has a higher priority than V-if. Therefore, it is not recommended to use both together. Because as you can imagine, every time you loop, you loop first, and then you judge, that’s also a performance loss

Loop output

In templates, you may often need to loop through items, so you will need to use the list loop. Such as:

<div id="app">
  <p class="item" v-for="item of itemList">{{item}}</p>
  <p v-for="item of message">{{item}}</p>
  <p v-for="item of 10">{{item}}</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script>
  var app = new Vue({
    el: "#app".data: {
      message: "helloworld".itemList: ["Yesterday"."Today"."Tomorrow"],}});</script>
Copy the code

List rendering doesn’t just work on arrays, it can loop through objects. In fact, this instruction can iterate over strings, numbers, etc.

  • When using the list render loop output, we recommend and enforce that you specify a unique key for each item. Because key is mainly used in Vue’s virtual DOM algorithm, VNodes are identified when the old and new nodes are compared. If keys are not used, Vue uses an algorithm that minimizes dynamic elements and tries to modify/reuse the same type of elements in place whenever possible. With a key, it rearranges the elements based on the change in the key and removes elements where the key does not exist. And child elements that have the same parent element must have a unique key. Duplicate keys cause render errors.

  • For several variation methods of array changes, Vue wraps the array change methods that will be listened for, so they will also trigger view updates. These covered methods include:

    • push()
    • pop()
    • shift()
    • unshift()
    • splice()
    • sort()
    • reverse()

Two-way binding of user input

You can use the V-model directive to create two-way data binding on forms ,

<input v-model="username" type="text" v-on:keydown.enter="addUser"/>
Copy the code

Due to the length of this section, it is recommended to refer to the official document: Form Input

The event processing

Events are a very core part of the front-end DOM. For traditional event processing, you might need to get elements, bind events, and write event handlers. Sometimes you also need to restrict the behavior of events and trigger scenarios for different situations, which is often a complex process in native development. In Vue, you only need to use the V-ON directive to bind events to the corresponding elements and use modifiers to control behavior constraints. Vue in order to solve a series of event processing process, it gives us a set of perfect simple event processing scheme. Here’s just one sentence to keep in mind for specific document event handling:

When a ViewModel is destroyed, all event handlers are automatically removed (unless you bind them yourself, such as some browser window events). You don’t have to worry about cleaning them.

What exactly is a template?

In fact, some of the things that we might talk about are in the official documentation, so this is just a summary. The last piece I want to talk about is what exactly we’re doing when we write htML-like templates. In fact, this is the last question I want to understand. It might be smart to say that Vue will help us compile and parse the template we wrote, and it is, in fact, the HTML we wrote will eventually be converted into the Render function and the virtual DOM. And then finally mount it

<div id="app">
   <! -- <p>{{message}}</p> -->
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script>
  var app = new Vue({
    // el: "#app",
    data: {
      message: "helloworld",},render(){
        with(this){return _c('div', {attrs: {"id":"app"}},[_c('p',[_v(_s(message))])])}
    }
}).$mount('#app')

console.log(app.$options.render);
</script>
Copy the code

The last

Finally, the basic syntax of vue.js and its ultimate nature are covered. It may not be as complete as you would expect, in fact, I felt it was worse than the official documentation when I was halfway through. But as a summary of the inductive article, I think it is still important to explain some of the basic chapters clearly. Next, I’ll probably plan out the component side of things and the subsequent routing related to VUex and some technical articles related to vUE componentization development. In general, I hope 2021 will be the year of mutual encouragement. If you want to write some articles together friends can pay attention to each other and supervision, spur each other to grow up, thank you ~!