♠ Vue template syntax and vue3 changes

Changes brought about by Vue3 (performance)

Data hijacking using Proxy

  • In Vue2 X, Vue2 uses object Defineproperty to hijack the getter and setter methods of data;
  • One defect of this method is that when adding or deleting attributes to an object, it cannot be hijacked and monitored;
  • So in vue2 X, we have to provide some special APIs, such as $set or $delete. In fact, they are hack methods, which also increases the cost for developers to learn new APIs;
  • And in vue3 X, Vue uses Proxy to hijack data;

Removed some unnecessary API s:

  • Removed $on, $off and $once on the instance;
  • Some features are removed, such as filter, inline template, etc;

Including compilation optimization:

  • Generate Block Tree, Slot compilation optimization and diff algorithm optimization;

Changes brought about by Vue3 (new API)

From Options API to Composition API:

  • In vue2 X, we will describe the component object through the Options API;
  • The Options API includes data, props, methods, computed, life cycle, and so on;
  • The big problem is that multiple logics may be in different places:
  • For example, a method will be used in created to modify the data of data, and the cohesion of the code is very poor;
  • The Composition API can process the associated code in the same place without looking for multiple Options;

Hooks function increases code reusability:

  • In vue2 X, we usually share logic among multiple components through mixins;
  • However, there is a big defect that mixins are also composed of a large number of Options, and multiple mixins will have the problem of naming conflict;
  • In vue3 In X, we can extract some independent logic through Hook function, and they can also be responsive;

Comparison between native counter and vue

view code
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h2 class="counter">0</h2>
    <button class="increment">+1</button>
    <button class="decrement">-1</button>

    <script>
      // 1. Get all elements
      const counterEl = document.querySelector(".counter");
      const incrementEl = document.querySelector(".increment");
      const decrementEl = document.querySelector(".decrement");

      // 2. Define variables
      let counter = 100;
      counterEl.innerHTML = counter;

      // 3. Click the monitor button
      incrementEl.addEventListener("click", () => {
        counter += 1;
        counterEl.innerHTML = counter;
      });
      decrementEl.addEventListener("click", () => {
        counter -= 1;
        counterEl.innerHTML = counter;
      });
    </script>
  </body>
</html>
view code
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  
  <div id="app">Ha ha ha</div>

  <script src="../js/vue.js"></script>
  <script>
    Vue.createApp({
      //Instead of '', use template string, which can wrap lines
      template: `
        <div>
          <h2>{{message}}</h2>
          <h2>{{counter}}</h2>
          <button @click='increment'>+1</button>
          <button @click='decrement'>-1</button>
        </div>
      `,
      //VUE2 can return {}, and vue3 needs to return function
      data: function() {
        return {
          //This data can be added to vue's responsive system (used in the template)
          message: "Hello World",
          counter: 100
        }
      },
      // Define a variety of methods
      methods: {
        increment() {
          console.log("Click+1");
          this.counter++;
        },
        decrement() {
          console.log("Click-1");
          this.counter--;
        }
      }
    }).mount('#app');
  </script>
</body>
</html>

Declarative and imperative

We will find that the modes and characteristics of native development and Vue development are completely different. In fact, two different programming paradigms are involved here:

  • Imperative programming and declarative programming;
  • Imperative programming focuses on "how to do", while declarative programming focuses on "what to do", and the framework (machine) completes the process of "how";

How do we operate in the native implementation process?

  • Every time we complete an operation, we need to write a code through JavaScript to give the browser an instruction;
  • This process of writing code is called imperative programming;
  • In the early development of native JavaScript and jQuery, we wrote code in this imperative way;

How do we operate in the implementation of Vue?

  • We will declare the required contents in the object passed in by createApp, such as template, data and method methods;
  • This process of writing code is called declarative programming;
  • At present, the programming modes of Vue, React and Angular are called declarative programming;

MVVM model

MVC and MVVM are both software architectures

  • MVC is the abbreviation of Model – View – Controller. It is a very framework architecture mode used in the early stage, such as iOS and front end;
  • MVVM is the abbreviation of model view view model. It is a very popular architecture mode at present;

In general, we often call Vue an MVVM framework. Vue officials have stated that although Vue does not fully comply with the MVVM model, the whole design is inspired by it.

template attribute

 

When using createApp, we pass in an object. Next, we will analyze in detail the meaning of the previously passed in attributes.

Template attribute: indicates the template information Vue needs to help us render:

  • At present, we can see that there are a lot of HTML tags in it. These tags will replace the innerHTML of the elements we mount (such as div with id app);
  • There are some strange syntax in the template, such as {}}, such as @ click, which are unique to the template;

However, the writing method of this template is a little too awkward, and the IDE may not have any tips, which hinders the efficiency of our programming.

Vue provides two ways:

Method 1: use script tag and mark its type as x-template;

Method 2: use any label (usually template label, because it will not be rendered by the browser) and set the id;

The template element is a mechanism for saving client-side content, which will not be rendered when the page is loaded, but can then be instantiated using JavaScript at run time;

At this time, in the createApp object, we need to start the passed template with #: if the string starts with #, it will be used as a querySelector, and the innerHTML of the matching element will be used as the template string;

view code
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  
  <div id="app">Ha ha ha</div>

  <script type="x-template" id="why">
    <div>
      <h2>{{message}}</h2>
      <h2>{{counter}}</h2>
      <button @click='increment'>+1</button>
      <button @click='decrement'>-1</button>
    </div>
  </script>

  <script src="../js/vue.js"></script>
  <script>
    //document.querySelector("#why")
    Vue.createApp({
      template: '#why',
      data: function() {
        return {
          message: "Hello World",
          counter: 100
        }
      },
      // Define a variety of methods
      methods: {
        increment() {
          console.log("Click+1");
          this.counter++;
        },
        decrement() {
          console.log("Click-1");
          this.counter--;
        }
      }
    }).mount('#app');
  </script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  
  <div id="app"></div>

  <template id="why">
    <div>
      <h2>{{message}}</h2>
      <h2>{{counter}}</h2>
      <button @click='increment'>+1</button>
      <button @click='decrement'>-1</button>
      <button @click="btnClick">Button</button>
    </div>
  </template>

  <script src="../js/vue.js"></script>
  <script>
    document.querySelector("#why")
    Vue.createApp({
      template: '#why',
      data: function() {
        return {
          message: "Hello World",
          counter: 100
        }
      },
      // Define a variety of methods
      methods: {
        increment() {
          console.log("Click+1");
          this.counter++;
        },
        decrement() {
          console.log("Click-1");
          this.counter--;
        },
        btnClick: () => {
          // this === window?  may not
          // When written as an arrow function, this is window
          // This is not bound in the arrow function, but if this is used in the function
          console.log(this);
        },
        btn2Click: function() {
          // this === window?  may not
          // When written as an arrow function, this is window
          // This is not bound in the arrow function, but if this is used in the function
          console.log(this);
        }
      }
    }).mount('#app');

  </script>
</body>
</html>

data attribute

The data attribute is passed into a function, and the function needs to return an object:

  • In vue2 X, you can also pass in an object (although the official recommendation is a function);
  • In vue3 X, a function must be passed in, otherwise an error will be reported directly in the browser;

The object returned in data will be hijacked by Vue's responsive system, and then the modification or access to the object will be processed in hijacking:

  • Therefore, we can access counter through {{counter}} in the template to obtain data from the object;
  • Therefore, when we modify the counter value, the {counter}} in the template will also change;

methods property

The methods attribute is an object. Usually, we will define many methods in this object:

These methods can be bound to the template template; In this method, we can use this keyword to directly access the properties of the object returned in data;

Keywords: Vue

Added by mohson on Fri, 07 Jan 2022 18:26:35 +0200