Recognize the application of Vue learning

tips:

  • The article will start with some basic usages as notes; you can also query for missing knowledge points during development;
  • There may be some deeper concepts, which may be linked to other articles in the form of links. If these concepts are not understood, they may not affect development.

Table of contents

1. Vue and progressive understanding

1.1. Progressive understanding

1.2. Vue and other popular frameworks

1.3. Choice of Vue2 and Vue3

2. Installation and introduction of Vue

2.1. CDN introduction

2.2. Download Vue source code import

3. Conceptual understanding of declarative programming and MVVM model

3.1. Declarative and imperative programming

3.2. MVVM model

4. Vue Basics - Options API

4.1.data attribute (data)

4.2.methods attribute (method)

4.2.1. Why can't the methods attribute use arrow functions? 

4.2.2.What does this in the methods attribute point to?

4.3.computed attribute (computed attribute)

4.3.1. Basic usage of computed

4.3.2. The difference between computed properties and methods

4.4.watch attribute (listener)

4.4.1.Watch configuration options

4.4.2. Other ways of watch

4.5. VSCode quickly generates code snippets

5. Vue template syntax

5.1.Mustache double brace syntax (interpolation syntax)

5.1.1. Basic use of interpolation syntax

5.1.2. JavaScript expression of interpolation syntax

5.2.v-once instruction (understand)

5.3.v-text command (understand)

5.4.v-html directive (understand)

5.5.v-pre instruction (understand)

5.6.v-cloak (understand)

5.7.v-bind directive (binding attribute)

5.7.1. Binding basic properties

5.7.2. Syntactic sugar for v-bind (abbreviation)

5.7.3. Binding class

5.7.4. Binding class-object syntax

5.7.5. Binding class-array syntax

5.7.6. Binding styles

5.7.7. Binding style-object syntax

5.7.8. Binding style-array syntax

5.7.9. Binding Element Attributes - Objects

5.8.v-on instruction (binding event)

5.8.1. Binding basic events

5.8.2. Syntactic sugar for v-on (abbreviation)

5.8.3.v-on binds multiple events

5.8.4. Parameter passing of v-on

5.8.5. Modifiers for v-on

5.9.v-if, v-else, v-else-if instructions (conditional rendering)

5.10. template element

5.11.v-show command (display elements)

5.11.1. The difference between v-show and v-if

5.12.v-for directive (list rendering)

5.12.1. Array usage of v-for 

5.12.2. Object usage of v-for

5.12.3. Other uses of v-for

5.12.4. template element

5.12.5. v-for array update detection

5.12.6. The role of the key in v-for

5.13. v-model directive (two-way binding)

5.13.1. Principle of v-model 

5.13.2.v-model binding textarea

5.13.3. v-model binding checkbox

5.13.4. v-model binding radio

5.13.5. v-model binding select

5.13.6. v-model modifier - lazy

5.13.7. v-model modifier-number

5.13.8. v-model modifier - trim

6. Vue componentization - component development basis

6.1. Understanding component development

6.2. Register global components

6.3. Component naming

6.4. Register local components

6.5. Development mode of Vue

6.5.1. Features of single-file components

6.5.2. Method of using single-file component (SFC)

6.5.3. Plug-in recommendations for single-file components (SFCs)

7. Vue componentization - CLI scaffolding 

7.1. Installation of Vue CLI

7.1.1. Installing the Vue CLI

7.1.2. Upgrading the Vue CLI

7.2. Vue CLI create project

7.3. Vue CLI running project 

7.3.1. Project directory structure

7.4. Coding mode using Vue CLI

7.5. VSCode quickly generates vue code


1. Vue and progressive understanding

Vue (pronounced /vju:/, similar to view) is a progressive Javascript framework for building user interfaces .

The full name is Vue.js or Vuejs, which is built on the basis of standard HTML, CSS and Javascript, and provides a life-like componentized programming model;

Helps you develop user interfaces efficiently.

Vue.js official website

1.1. Progressive understanding

In the explanation for Vue.js, a concept is involved: progressive

Vue is a progressive Javascript framework, which means that we can introduce and use Vue a little bit in the project, instead of using Vue to develop the entire project. 

When developing a project, there may be many functions. You can choose to use Vue to develop some parts, and other parts to use other frameworks to develop; you can use Vue to refactor the functions developed with other frameworks step by step, and the functions developed with other frameworks are also available. will be affected. 

Borrow [One Night Maple Forest] Big Brother's understanding of the progressive framework : you can only use a part of me, instead of using all my parts if you use this point of me.

1.2. Vue and other popular frameworks

Currently the three most popular front-end frameworks: Vue, React, Angular

  • Vue has the highest market share in the domestic market, and almost all front-end positions will require Vue;
  • React has a very high market share at home and abroad; it is also a framework that front-end engineers must learn. Generally large companies use more;
  • Angular has a high entry threshold, needs to learn typescript, and has a relatively low domestic market share;

All three are excellent frameworks, but Vue and React are temporarily more suitable frameworks for learning in terms of the difficulty of getting started as a beginner and the current career development direction.

The following frame data comparison

Google index
Baidu Index
npm downloads
GitHub data

1.3. Choice of Vue2 and Vue3

On September 19, 2020, Vue3 released the official version, which has many advantages:

  • better performance
  • smaller size
  • Better TypeScript integration
  • Better API design

Now is the right time to learn Vue3, Vue3 is currently a stable version, and Vue3 has become the default installed version on February 7, 2022;

Many companies are already using Vue3 for development of their new projects, and almost all kinds of Vue3-related questions are asked during interviews.

And the author You Yuxi also suggested learning Vue3 directly, and said that the basic concepts are exactly the same.

2. Installation and introduction of Vue

After explaining the basic introduction of Vue, the next step is to start encountering Vue.

Vue is a Javascript library. Think of it as a packaged library (similar to jQuery), just reference and use it in the project.

Ways to install and use Vue:

  1. Introduce through CDN in the page ;
  2. Download Vue's JavaScript file and manually import it yourself;
  3. Install and use through the npm package management tool ;
  4. Create a project directly through Vue CLI and use it;

In the early stage, the first two introduction methods are used to learn Vue syntax, and the latter two are used after learning the npm package management tool and Vue CLI scaffolding.

As a beginner, you need to pay attention to: the first two methods are written in the html file. If you are using vscode,! Add the Tab key to quickly build an html structure. The following codes are temporarily written in the body element.

2.1. CDN introduction

Vue's CDN introduction

<script src="https://unpkg.com/vue@next"></script>

Hello vue3 display implementation, don't care about the vue-related code, just focus on CDN import.

<div id="app"></div>
  <script src="https://unpkg.com/vue@next"></script>
  <script>
    //vue相关的代码
    const app = Vue.createApp({
      template: '<h2>hello vue3</h2>'
    });
    //将app挂载到id为app的div上
    app.mount("#app");
  </script>

 You can see that the browser runs the content of the template in the Vue code.

2.2. Download Vue source code import

 Open the link of https://unpkg.com/vue@next Vue source code and copy all the codes in it.

 Create a new js file, copy the code into it, and name it vue.js.

 Use the script tag to import the file just now.

  <div id="app"></div>
  //引入vue.js文件
  <script src="./vue.js"></script>

  <script>
    //vue相关的代码
    const app = Vue.createApp({
      template: '<h2>hello vue3</h2>'
    });
    //将app挂载到id为app的div上
    app.mount("#app");
  </script>

 In the early learning process, it is recommended to use the Vue source code import method, because the CDN reference may be affected by the network, and it is more efficient to use the local Vue source code.

3. Conceptual understanding of declarative programming and MVVM model

These two concepts may not be practically applied in development, but programming ideas are also a very important part of programming, and these concepts are occasionally mentioned in interview questions.

3.1. Declarative and imperative programming

If you have used native JavaScript to develop some functions, you may soon understand the difference between imperative programming and declarative programming. Borrow [Blank Paper] Big Brother's article to basically understand the difference between imperative programming and declarative programming

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

  • Declarative and imperative programming
  • Imperative programming focuses on " how to do ", and the developer completes the entire process;
  • Declarative programming focuses on " what to do ", and the process of "how" is completed by the framework (machine);

 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 process of native JavaScript and jQuery, we all wrote code in this imperative way;

How do we operate during the implementation of Vue?

  • We will declare the required content in the object passed in by createApp , template template, data data, method methods;
  • This process of writing code is called declarative programming ;
  • The current programming mode of Vue, React, Angular, and applets is called declarative programming;

 Vue's programming model is declarative programming.

3.2. MVVM model

Both MVC and MVVM are a software architecture

  • MVC is the abbreviation of Model-View-Controller, which is a very widely used architectural pattern in the early stage, such as iOS and front-end;
  • MVVM is the abbreviation of Model-View-ViewModel, which is a very popular architectural pattern; usually, we often call Vue a MVVM framework;
  • Vue officials actually stated that although Vue does not fully comply with the MVVM model, the entire design is inspired by it .

MVVM is to abstract the state and behavior of the View in it, and let us separate the view UI from the business logic. 

View layer

The view layer, usually the DOM layer, displays various information to the user.

Model layer

The data layer may be custom data, or it may be data requested from the server or the network.

ViewModel layer

The view model layer is the bridge between view and model;

It implements Data Binding, data binding, and reflects changes in the model to the view in real time;

It implements DOM Listener, which is DOM monitoring. When some events occur in DOM, it can monitor and change the corresponding data.

4. Vue Basics - Options API

I have learned to introduce Vue, and I have explained some programming concepts, so I can learn the basics of Vue.

4.1.data attribute (data)

The data attribute is used frequently, so you can learn how to use this attribute first. The data is mainly used to store data .

<div id="app">
    <h2>{
   
   {message}}</h2>
  </div>
  <script src="./vue.js"></script>
  <script>
    //vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          message: "aaaa"
        }
      }
    });
    //将app挂载到id为app的div上
    app.mount("#app");

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 (the official recommendation is to pass in a function);
  • In Vue3.x , a function must be passed in , otherwise an error will be reported directly in the browser ;

We are learning Vue3 now, so we need to pass in a function that returns an object of data.

data: function(){
    return {
        message: "message"
    }    
}

4.2.methods attribute (method)

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

  • These methods can be bound into templates ;
  • In this method, we can use the this keyword to directly access the properties of the object returned by data;
<div id="app">
    <h2>{
   
   {message}}</h2>
  </div>
  <script src="./vue.js"></script>
  <script>
    //vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          message: "aaaa"
        }
      },
//可以编写方法
      methods: {
        messMethod() {
           console.log(this.message)
        }
      }
    });
    //将app挂载到id为app的div上
    app.mount("#app");

In this example, the messMethod method is defined and the message in data is used.

4.2.1. Why can't the methods attribute use arrow functions? 

The following is the explanation given by the official documentation.

If you haven't learned the relevant content of this binding, you may not understand it. There are many knowledge points that have not been learned, such as: arrow function and scope (written by Ben Meng). It’s okay if you don’t understand, but remember that methods must not use arrow functions .

//箭头函数类似于这种
var methods = () => {
    console.log("里面可以写内容")
}

We use data to return the data in the object in methods:

  • Then this this must have a value , and it should be possible to get the data in the data return object through this .

So can our this be a window?

  • It cannot be window , because we cannot get the data in the data return object in window;
  • But if we use the arrow function , then this this will be window ;

Why is it window?

  • This involves the use of this search rules by the arrow function , which will find this in its own upper layer ;
  • In the end, what I just found is the this that the script acts on, so it is window;

4.2.2.What does this in the methods attribute point to?

This piece of content is also difficult to understand. You can first understand the pointing rules of this . In fact, the source code of Vue traverses all the functions in methods and binds this through bind .

So methods can use the data in data.

4.3.computed attribute (computed attribute)

We know that some data in data can be displayed directly through interpolation syntax in the template .

However, in some cases, we may need to perform some conversion on the data before displaying, or combine multiple data for display;

  • For example, we need to perform operations on multiple data data, ternary operators to determine the results, and display the data after some transformation;
  • It is very convenient to use expressions in templates, but they are designed for simple operations ;
  • Putting too much logic in the template will make the template heavy and difficult to maintain ;
  • And if it is used in multiple places, there will be a lot of repeated code;

Is there any way we can extract the logic out?

  • Yes, one way is to extract the logic into a method and put it in the options of the methods;
  • However, this approach has an intuitive disadvantage, that is, all data usage processes will become a method call ;
  • Another way is to use the computed property computed ;

Vue official said: For any complex logic that includes responsive data , you should use computed properties . 

4.3.1. Basic usage of computed

 If we want to reverse a string, we can use computed.

<div id="app">
    <h2>{
   
   {string}}</h2>
  </div>
  <script src="./vue.js"></script>
  <script>
    //vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          message: "first second"
        }
      },
      computed: {
        string() {
          return this.message.split(" ").reverse().join(" ")
        }
      }
    });
    //将app挂载到id为app的div上
    app.mount("#app");

Notice:

  • A computed property looks like a function, but we don't need to add () when using it ;
  • And the calculated property is cached

4.3.2. The difference between computed properties and methods

<div id="app">
    <!-- 使用计算属性 -->
    <h2>{
   
   {string}}</h2>
    <h2>{
   
   {string}}</h2>
    <h2>{
   
   {string}}</h2>
    <!-- 使用方法 -->
    <h2>{
   
   {getString()}}</h2>
    <h2>{
   
   {getString()}}</h2>
    <h2>{
   
   {getString()}}</h2>
  </div>
  <script src="./vue.js"></script>
  <script>
    //vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          message: "first second"
        }
      },
      methods: {
        getString() {   
          console.log('调用methods');     
          return this.message.split(" ").reverse().join(" ")
        }
      },
      computed: {
        string() {
          console.log('调用computed');
          return this.message.split(" ").reverse().join(" ")
        }
      }
    });
    //将app挂载到id为app的div上
    app.mount("#app");
  </script>

It looks similar, but computed properties are cached, but methods are not.

 

It can be seen that although the data is displayed three times, computed is called only once, while methods are called three times.

  • This is because computed properties are cached based on their dependencies ;
  • When the data does not change , the calculated attribute does not need to be recalculated ;
  • However, if the dependent data changes , the calculated property will still be recalculated when used ;

Summarize the difference between computed and methods: 

  1. Computed properties are cached, but methods are not. Computed properties perform better when a piece of data is used multiple times.
  2. There is no need to add parentheses after the calculated attribute is placed in the interpolation syntax, but the method needs it.

4.4.watch attribute (listener)

During development, we define data in the object returned by data , and this data is bound to the template through the difference syntax and other methods;

When the data changes , the template will automatically update to display the latest data ;

If we want to listen to a certain data change in the code logic , we need to use the listener watch to listen .

<div id="app">
    <h2>{
   
   {message}}</h2>
    <h2>{
   
   {info.name}} - {
   
   {info.age}}</h2>
    <button @click="btnClick">按钮</button>
  </div>
  <script src="./vue.js"></script>
  <script>
    //vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          message: "aaaa",
          info: {
            name: "zzz",
            age: 18
          }
        }
      },
      methods: {
        btnClick() {
          this.message = "bbbb",
          this.info = {name: "www", age: 19}
        }
      },
      // 监听message和info
      watch: {
        message(newValue, oldValue){
          console.log(newValue, oldValue);
        },
        info(newValue, oldValue) {
          console.log({...newValue});
        }
      }
    });
    //将app挂载到id为app的div上
    app.mount("#app");

Use the string, array, or object you want to listen to as the function name of the watch.

At the same time, this function has two parameters:

  • The first parameter is the changed value;
  • The second parameter is the old value.

4.4.1.Watch configuration options

<div id="app">
    <h2>{
   
   {message}}</h2>
    <h2>{
   
   {info.name}} - {
   
   {info.age}}</h2>
    <button @click="btnClick">按钮</button>
  </div>
  <script src="./vue.js"></script>
  <script>
    //vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          message: "aaaa",
          info: {
            name: "zzz",
            age: 18
          }
        }
      },
      methods: {
        btnClick() {
          this.message = "bbbb",
          this.info.name = "cccc"
        }
      },
      // 监听message
      watch: {
        message(newValue, oldValue){
          console.log(newValue, oldValue);
        },
        info(newValue, oldValue) {
          console.log({...newValue});
        }
      }
    });
    //将app挂载到id为app的div上
    app.mount("#app");
  </script>

 The above example: When we click the button, the value of info.name will be modified; at this time, we use watch to listen to info, can we listen to it? The answer is no .

This is because by default, watch is only listening to info reference changes, and will not respond to changes in internal properties:

  • At this time we can use an option deep for deeper listening ;
  • Note that we said earlier that the listening attribute in the watch can also be an Object;

There is another attribute, which is expected to be executed immediately at the beginning:

  • At this time we use the immediate option ;
  • At this time, no matter whether there is any change in the subsequent data, the listening function will be executed once in a limited time ;
watch: {
        message(newValue, oldValue){
          console.log(newValue, oldValue);
        },
        info:{
          handler(newValue, oldValue) {
            console.log({...newValue}, {...oldValue});
          },
          deep: true,
          immediate: true
        }
      }

 

4.4.2. Other ways of watch

 There is also a syntax for listening to object values, which is written in watch.

"info.name": function(newValue, oldValue) {
          console.log(newValue, oldValue);
        }

Another way is to use the $watch API:

We can use this.$watches to listen in the created life cycle (will be discussed later);

The first parameter is the source to listen to;

The second parameter is the listened callback function callback;

The third parameter is additional other options, such as deep, immediate;

4.5. VSCode quickly generates code snippets

In the process of practicing Vue, some code snippets need to be written frequently. We can generate a code snippet in VSCode , which is convenient for us to quickly generate .

The code snippets in VSCode have a fixed format, so we usually use an online tool to complete it.

The specific steps are as follows:

  • The first step is to copy the code that you need to generate a code snippet;
<!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">
    <h2>{
   
   {message}}</h2>
  </div>
  <script src="./vue.js"></script>
  <script>
    //vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          message: "aaaa"
        }
      }
    });
    //将app挂载到id为app的div上
    app.mount("#app");
  </script>
</body>
</html>
  • In the second step, https://snippet-generator.app/ generates code snippets in the website;

 Copy the content generated on the right.

  • The third step is to configure the code snippet in VSCode;

 Open VSCode, menu bar => file => preferences => user fragment (or configure user code fragment);

 Paste the copied code into it;

 In this way, when the vueapp is entered on the html page, the corresponding code fragment will be generated.

5. Vue template syntax

In most cases, Vue's development mode uses HTML-based template syntax ;

In the template, developers are allowed to bind the DOM and the data of the underlying component instance in a declarative manner ;

Under the hood, Vue compiles templates into virtual DOM rendering functions .

5.1.Mustache double brace syntax (interpolation syntax)

If we want to display the data into the template, Mustache double braces syntax interpolation is the most used;

When the data in data changes , the corresponding content will also be updated .

<script src="./vue.js"></script>
  <script>
    //vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          message: "aaaa bbbb",
          counter: 100,
          age: 20
        }
      }
    });
    //将app挂载到id为app的div上
    app.mount("#app");
  </script>

5.1.1. Basic use of interpolation syntax

Spaces can be added inside the double curly braces of the interpolation syntax , and other content can also be inserted into HTML elements .

  <div id="app">
    <!-- 基本使用 -->
    <h2>{
   
   {message}}</h2>
    <!-- 插值语法里面可以加空格 -->
    <h2>也可以插入其他内容 {
   
   { counter }}</h2>
  </div>

5.1.2. JavaScript expression of interpolation syntax

The interpolation syntax can not only be an attribute in data, but also a JavaScript expression, and a function in methods can also be called.

    <!-- 表达式 -->
    <h2>{
   
   { counter * 2 }}</h2>
    <h2>{
   
   { message.split(" ") }}</h2>
    <h2>{
   
   { age>18 ? "成年" : "未成年" }}</h2>

 

5.2.v-once instruction (understand)

This instruction is rarely used, mainly for specifying elements or components to be rendered only once

When the data changes, the element or component and all its child elements will be regarded as static content and skipped;

This instruction can be used for performance optimization;

<div id="app">
    <h2 v-once >count: {
   
   {count}}</h2>
    <button @click="add">+</button>
  </div>
  <script src="./vue.js"></script>
  <script>
    //vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          count: 0
        }
      },
      methods: {
        add(){
          this.count++
        }
      }
    });
    //将app挂载到id为app的div上
    app.mount("#app");
  </script>

If the v-once command is not added, after the button is clicked, the add method in methods will be triggered, and the count will increase automatically. But this element is only rendered once, so count will be 0 no matter how many times the button is pressed.

5.3.v-text command (understand)

The v-text instruction is also used less, which is similar to the double brace syntax, but not as flexible as the double brace syntax.

<div id="app">
    <h2>前面可以写{
   
   { message }}后面也可以</h2>
    <h2 v-text="message"></h2>
  </div>
  <script src="./vue.js"></script>
  <script>
    //vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          message: "aaaa"
        }
      }
    });
    //将app挂载到id为app的div上
    app.mount("#app");
  </script>

5.4.v-html directive (understand)

By default, if the content we display is HTML , Vue will not parse it specially.

If we want this content to be parsed by Vue , we can use v-html to display it;

<div id="app">
    <h2>{
   
   {content}}</h2>
    <h2 v-html="content"></h2>
  </div>
  <script src="./vue.js"></script>
  <script>
    //vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          content: `<span style="color: red; font-size: 30px">哈哈哈</span>`
        }
      }
    });
    //将app挂载到id为app的div上
    app.mount("#app");
  </script>

If you use v-html, you can parse it. If you don’t use v-html, you can directly output the html tags.

In this case, the template string (` `) is useful, so you can learn about its usage scenarios.

5.5.v-pre instruction (understand)

Sometimes you want to use { {}} in html tags , but by default it will be parsed into double curly braces syntax, you can add v-pre in the tag.

<div id="app">
    <h2>{
   
   {message}}</h2>
    <h2 v-pre>{
   
   {message}}</h2>
  </div>
  <script src="./vue.js"></script>
  <script>
    //vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          message: "aaaa"
        }
      }
    });
    //将app挂载到id为app的div上
    app.mount("#app");

5.6.v-cloak (understand)

Cloak means cloak, and this instruction stays on the element until the associated component instance finishes compiling.

If you add a timer to Vue compilation to simulate slow compilation when the network is not good.

<div id="app">
    <h2>{
   
   {message}}</h2>
  </div>
  <script src="./vue.js"></script>
  <script>
    //vue相关的代码
    setTimeout(() => {
      const app = Vue.createApp({
      data: function(){
        return {
          message: "aaaa"
        }
      }
    });
    //将app挂载到id为app的div上
    app.mount("#app");
    }, 2000);

2 seconds ago, it was found that such a display would appear on the page, which was unfriendly to users, so v-cloak and CSS rules were used to solve this problem.

<style>
    [v-cloak] {
      display: none;
    }
  </style>
<div id="app">
    <h2 v-cloak>{
   
   {message}}</h2>
</div>

Put v-cloak on the element that might be loaded and style it.

5.7.v-bind directive (binding attribute)

From here on are frequently used instructions, so you must understand them well.

The previous series of instructions mainly insert values ​​into the template content . But in addition to the content needs to be determined dynamically, we also want to dynamically bind certain attributes. We use v-bind to bind properties .

  • For example, dynamically bind the href attribute of the a element;
  • For example, dynamically bind the src attribute of the img element.

v-bind syntactic sugar (shorthand) form:    :   

5.7.1. Binding basic properties

v-bind is used to bind one or more attribute values.

<div id="app">
    <a v-bind:href="href">搜索一下</a>
  </div>
  <script src="./vue.js"></script>
  <script>
    //vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          href: "https://www.baidu.com"
        }
      }
    });
    //将app挂载到id为app的div上
    app.mount("#app");

The href attribute in the a element plus the v-bind command can dynamically change the URL in the href , and put the URL of the href in the data.

5.7.2. Syntactic sugar for v-bind (abbreviation)

In development, we often use syntactic sugar (from Franco Crayon Xiaoqiang) to write, and syntactic sugar will be more concise.

    <a v-bind:href="href">搜索一下</a>
    
    <a :href="href">搜索一下</a>

5.7.3. Binding class

During development, sometimes we can dynamically change the element class to change the style.

<style>
    .active {
      color: red;
    }
</style>
<body>
  <div id="app">
    <button :class="isActive ? 'active' : ''" @click="activeClick">按钮</button>
  </div>
  <script src="./vue.js"></script>
  <script>
    //vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          isActive: false
        }
      },
      methods: {
        activeClick() {
          this.isActive = !this.isActive
        }
      }
    });
    //将app挂载到id为app的div上
    app.mount("#app");
  </script>
</body>

In this example, the activeClick event is triggered after the button is clicked, and isActive is set to true. The class is dynamically bound with v-bind, the ternary expression isActive is true, and the class is active, so the color of the text becomes red.

5.7.4. Binding class-object syntax

We can pass an object to dynamically switch classes.

<div class="aaa" :class="{nba: isActive, 'cba': true}">2222</div>

Multiple key-value pairs {class class: boolean value} can be passed in.

In the example above

  • The aaa class without v-bind can be added to this div element regardless of the state.
  • The class with v-bind can judge whether to add the class name to the div element according to the following boolean value.
  • Among them, isActive can be the boolean class value in the data attribute.

5.7.5. Binding class-array syntax

We can pass an array to :class to apply a list of classes;

<!-- 直接传入一个数组 -->
<h2 :class="['abc', className]">数组语法</h2>

<!-- 数组中也可以使用三元运算符或者绑定变量 -->
<h2 :class="['abc', className, isActive? 'acitve' : '']">数组语法</h2>

<!-- 数组中使用对象语法 -->
<h2 :class="['abc', className, {'active': isActive}]">数组语法</h2>


//vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          isActive: true
          className: "cba"
        }
      },

If it is not stored in the form of a string in the array, such as the className in the example, the className in the data will be used.

5.7.6. Binding styles

We can use v-bind:style to bind some CSS inline styles :

  • Some styles we need to decide dynamically according to the data ;
  • Such as the color and size of a certain text.

The CSS property (property name) in the binding style can be named in camel case or dash-separated (need to be wrapped in quotation marks).

<h2 :style="{fontSize: '40px' , 'background-Color': 'blue'}">{
   
   {message}}</h2>
  • If you use camel case, you don't need to use quotation marks, and you need to use quotation marks when you use dashes to separate;
  • Separate multiple attributes with commas .

5.7.7. Binding style-object syntax

  • We can pass in an object that determines the content;
  • CSS attribute values ​​can also come from data;
  • Even define an object directly in data.
<div id="app">
    <!-- 传入一个对象,并且对象内容都是确定的 -->
    <div :style="{color: 'red' , fontSize: '40px' , 'background-Color': 'blue'}">{
   
   {message}}</div>
    <!-- css属性值可以来自data,fontSize中的size来自data -->
    <div :style="{color: 'red' , fontSize: size +'px' , 'background-Color': 'blue'}">{
   
   {message}}</div>
    <!-- 直接在data定义好一个对象 -->
    <div :style="styleObj">{
   
   {message}}</div>
  </div>
  <script src="./vue.js"></script>
  <script>
    //vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          message: "aaaa",
          size: 20,
          styleObj:{color: 'green', fontSize: '80px', backgroundColor: 'pink'}
        }
      }
    });
    //将app挂载到id为app的div上
    app.mount("#app");

5.7.8. Binding style-array syntax

The array can contain multiple objects, define multiple style objects in data, and apply multiple style objects to one element.

<!-- 直接在data定义好两个对象 -->
<div :style="[styleObj1, styleObj2]">{
   
   {message}}</div>

//vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          styleObj1:{color: 'green', backgroundColor: 'pink'},
          styleObj2:{fontSize: '80px'}
        }
      }
    });
    //将app挂载到id为app的div上
    app.mount("#app");

 

5.7.9. Binding Element Attributes - Objects

What should we do if we want to bind all properties of an object to all properties of an element?

We can bind an object directly using v-bind;

<div v-bind="infos">{
   
   {message}}</div>

//vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          infos: {name: 'zzz', age: 20, height: 1.11}
        }
      }
    });
    //将app挂载到id为app的div上
    app.mount("#app");

5.8.v-on instruction (binding event)

The use of v-on:

abbreviation:@

Expected: Function | Inline Statement | Object

Parameters: event

Modifiers:

  • .stop - Call event.stopPropagation().
  • .prevent - call event.preventDefault().
  • .capture - Use capture mode when adding event listeners.
  • .self - Only fires the callback if the event is fired from the element itself to which the listener is bound.
  • .{keyAlias} - Callback is fired only if the event was fired from a specific key.
  • .once - triggers the callback only once.
  • .left - Fires only when the left mouse button is clicked.
  • .right - Fires only when the right mouse button is clicked.
  • .middle - Fires only when the middle mouse button is clicked.
  • .passive - { passive: true } mode add listener

Usage: bind event listener

5.8.1. Binding basic events

In the binding event, you can bind an expression or a method.

In actual development, the binding method is more commonly used.

<div id="app">
    <div>{
   
   {counter1}}</div>
    <!-- 绑定表达式 -->
    <button v-on:click="counter1++">+</button>
    <div>{
   
   {counter2}}</div>
    <!-- 绑定方法 -->
    <button v-on:click="btnClick">+</button>

  </div>
  <script src="./vue.js"></script>
  <script>
    //vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          counter1: 0,
          counter2: 0
        }
      },
      methods: {
        btnClick() {
          this.counter2 ++
        }
      },
    });
    //将app挂载到id为app的div上
    app.mount("#app");

The click event is the most frequently used event, and the following are some events that may be used.

focus event

event name when to trigger
focus Element gets focus (no bubbling)
blur Element loses focus (does not bubble)

form event

event name when to trigger
reset When the reset button is clicked
submit Click the submit button

keyboard events

event name when to trigger
keydown press any key
keypress Any key except Shift, Fn, CapsLock is held down (continuous trigger)
keyup release any key

mouse event

event name when to trigger
click Press and release any mouse button on the element.
contextmenu Right click (triggers before the context menu is shown).
dblclick Double-click the mouse button on the element.
mousedown Press any mouse button on the element.
mouseenter The pointer moves to the element with event listeners.
mouseleave The pointer moves outside the bounds of the element (without bubbling).
mousemove Fires continuously as the pointer moves within the element.
mouseover The pointer moves to the element with event listeners or its child elements.
mouseout The pointer moves out of the element, or onto its child elements.
mouseup Release any mouse button on the element.

5.8.2. Syntactic sugar for v-on (abbreviation)

v-on:click can be written as @click, which is its grammatical sugar:

<button @click="btnClick">+</button>

5.8.3.v-on binds multiple events

If we want an element to bind multiple events, we can pass in an object. But don't .

<button v-on="{click: btnClick, mousemove: mouseMove}">+</button>

5.8.4. Parameter passing of v-on

When defining methods in methods for @click calls, you need to pay attention to parameter issues:

  • Case 1: If the method does not require additional parameters, then the () after the method may not be added . But note: if there is a parameter in the method itself, the native event event parameter will be passed in by default;
<button @click="btnClick1">按钮</button>
btnClick1(e) {
  console.log(e);
},

  • Case 2: If you need to pass in a certain parameter and event at the same time, you can pass in the event through $event .
<button @click="btnClick2($event, 'other')">按钮</button>
btnClick2(event, message) {
    console.log(event, message);
}

 

5.8.5. Modifiers for v-on

v-on supports modifiers , which are equivalent to some special handling of events:

  • .stop - Call event.stopPropagation(). cancel bubbling event
  • .prevent - call event.preventDefault(). cancel default event
  • .capture - Use capture mode when adding event listeners.
  • .self - Only fires the callback if the event is fired from the element itself to which the listener is bound.
  • .{keyAlias} - Callback is fired only if the event was fired from a specific key.
  • .once - triggers the callback only once.
  • .left - Fires only when the left mouse button is clicked.
  • .right - Fires only when the right mouse button is clicked.
  • .middle - Fires only when the middle mouse button is clicked.
  • .passive - { passive: true } mode add listener
<button @click.stop="btnClick">按钮</button>

5.9.v-if, v-else, v-else-if instructions (conditional rendering)

v-if, v-else, v-else-if are used to render the content of a block according to conditions :

These contents will only be rendered when the condition is true ;

These three instructions are similar to JavaScript conditional statements if, else, else if;

    <h2 v-if="score > 90">优秀</h2>
    <h2 v-else-if="score > 80">良好</h2>
    <h2 v-else-if="score > 60">及格</h2>
    <h2 v-else>不及格</h2>
  • v-if is lazy;
  • When the condition is false, the judged content will not be rendered at all or will be destroyed ;
  • When the condition is true, the content in the conditional block will actually be rendered ;
  • So v-if will render the content after judging the condition .

5.10. template element

Because v-if is a directive, it must be added to an element:

But what if we want to switch multiple elements?

At this point we render div, but we don't want elements like div to be rendered ; at this time, we can choose to use template ;

The template element can be used as an invisible wrapper element and used in v-if or other conditional rendering instructions, but the template will not be rendered in the end.

<div id="app">
    <template v-if="show">
      <h2>v-if</h2>
      <h2>v-if</h2>
      <h2>v-if</h2>
    </template>
    <template v-else>
      <h2>v-else</h2>
      <h2>v-else</h2>
      <h2>v-else</h2>
    </template>
  </div>
  <script src="./vue.js"></script>
  <script>
    //vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          show: true
        }
      }
    });
    //将app挂载到id为app的div上
    app.mount("#app");
  </script>

 After the condition is judged, the template will not be rendered to the DOM .

5.11.v-show command (display elements)

The usage of v-show and v-if seems to be consistent, and it is also based on a condition to determine whether to display an element or component:

<div id="app">
    <h2 v-show="isShow">v-show</h2>
  </div>
  <script src="./vue.js"></script>
  <script>
    //vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          isShow: true
        }
      }
    });
    //将app挂载到id为app的div上
    app.mount("#app");
  </script>

5.11.1. The difference between v-show and v-if

First, the difference in usage :

  • v-show does not support template;
  • v-show cannot be used with v-else;

Second, the essential difference:

  • Regardless of whether the v-show element needs to be displayed on the browser or not, its DOM actually exists , and it is only switched through the display property of CSS ;
  • v-if When the condition is false, its corresponding native will not be rendered into the DOM at all;
<div id="app">
    <h2 v-if="ifShow">v-if</h2>
    <h2 v-show="isShow">v-show</h2>
  </div>
  <script src="./vue.js"></script>
  <script>
    //vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          ifShow: false,
          isShow: false
        }
      }
    });
    //将app挂载到id为app的div上
    app.mount("#app");

In this case, ifShow and isShow are both false, neither element will be displayed, but the DOM tree has some differences.

The style="display: none" in h2 rendered with v-show confirms the display attribute above to switch the display and hiding of elements. 

How to choose during development?

  • If our native needs to switch between display and hide frequently , then use v-show ;
  • If switching will not occur frequently , then use v-if ;

5.12.v-for directive (list rendering)

In real development, we often get a set of data from the server and need to render it.

At this time we can use v-for to complete;

v-for is similar to JavaScript's for loop, which can be used to traverse a set of data;

 Just like this page, it would be too troublesome to write the data for each album. So we can put all the data in an array or object, and use v-for list rendering when we need to develop such a page.

5.12.1. Array usage of v-for 

 The basic format of v-for is item in array :

Arrays usually come from data and prop  , and item is an alias we give to each element , and this alias can also be defined by ourselves.

Use item in array to get the elements of the array 

<div id="app">    
    <h2 v-for="item in array">{
   
   {item}}</h2>
  </div>
  <script src="./vue.js"></script>
  <script>
    //vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          array: ["first", "second", "third", "fourth"]
        }
      }
    });
    //将app挂载到id为app的div上
    app.mount("#app");
  </script>

 In the above case, v-for is used to traverse the array array, and the array array is defined in data.

Sometimes you need to get the index of the array  when traversing the array :

If we need an index, we can use the format (item, index) in array :

 The array element item item is at the front , and the index item index is at the back .

Use (item, index) in array to get the elements and objects of the array

<div id="app">
    <h2 v-for="(item, index) in array" >{
   
   {index}} - {
   
   {item}}</h2>
  </div>
  <script src="./vue.js"></script>
  <script>
    //vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          array: ["first", "second", "third", "fourth"]
        }
      }
    });
    //将app挂载到id为app的div上
    app.mount("#app");
  </script>

The index and item can be output using the brace syntax.

5.12.2. Object usage of v-for

v-for can have three parameters when traversing objects , namely value, key, and index .

Use value in object to get the value of the object

<div id="app">
    <h2 v-for="value in obj">{
   
   {value}}</h2>
  </div>
  <script src="./vue.js"></script>
  <script>
    //vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          obj: {
            key1 : 'value1',
            key2 : 'value2',
            key3 : 'value3',
            key4 : 'value4'
          }
        }
      }
    });
    //将app挂载到id为app的div上
    app.mount("#app");
  </script>

 When it is a value, it defaults to the value value.

 Use (value, key) in object to get the value and key of the object

<div id="app">
    <h2 v-for="(value, key) in obj">{
   
   {key}}-{
   
   {value}}</h2>
  </div>
  <script src="./vue.js"></script>
  <script>
    //vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          obj: {
            key1 : 'value1',
            key2 : 'value2',
            key3 : 'value3',
            key4 : 'value4'
          }
        }
      }
    });
    //将app挂载到id为app的div上
    app.mount("#app");
  </script>

Pay attention to the order. Generally speaking, the more important ones are placed first. For objects, the value is the most important, followed by the key.

 

 Use (value, key, index) in object to get the value, key and index of the object

<div id="app">
    <h2 v-for="(value, key, index) in obj">{
   
   {index}}-{
   
   {key}}-{
   
   {value}}</h2>
  </div>
  <script src="./vue.js"></script>
  <script>
    //vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          obj: {
            key1 : 'value1',
            key2 : 'value2',
            key3 : 'value3',
            key4 : 'value4'
          }
        }
      }
    });
    //将app挂载到id为app的div上
    app.mount("#app");
  </script>

We seldom take the index value of the object, so put the index index parameter at the end.

The traversal of arrays and objects is still used a lot during development, and the impression will be deeper if you practice it yourself.

5.12.3. Other uses of v-for

v-for also supports number traversal: each item is a number;

v-for can also traverse other iterable objects (Iterable).

These usages are used relatively rarely, demonstrating the traversal of a number.

<span v-for="item in 10">{
   
   {item}}</span>

5.12.4. template element

Similar to v-if, you can use the template element to loop through a piece of content that contains multiple elements:

We use templates to wrap multiple elements instead of divs;

<div id="app">
    <template v-for="(value, key) in info">
      <li>{
   
   {key}}</li>
      <li>{
   
   {value}}</li>
      <br/>
    </template>
  </div>
  <script src="./vue.js"></script>
  <script>
    //vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          info: {
            key1: 'value1',
            key2: 'value2'
          }
        }
      }
    });
    //将app挂载到id为app的div上
    app.mount("#app");
  </script>

 After the compilation is complete, the template will disappear and will not be rendered on the DOM tree.

5.12.5. v-for array update detection

Vue wraps listened array mutation methods so they will also trigger view updates .

These wrapped methods include: push() pop() shift() unshift() splice() sort() reverse()  . If you haven't learned about these array methods , you can take a look first. 

We write a case to check whether the corresponding view will be updated when the array changes.

<div id="app">
    <h2 v-for="item in array">{
   
   {item}}</h2>
    <button @click="addClick">添加</button>
  </div>
  <script src="./vue.js"></script>
  <script>
    //vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          array:["a","b","c"]
        }
      },
      methods: {
        addClick() {
          this.array.push('d')
        }
      },
    });
    //将app挂载到id为app的div上
    app.mount("#app");
  </script>

 When we click the button, put d behind the array, and the array rendered by v-for will change.

Explain that when using push() pop() shift() unshift() splice() sort() reverse() to change the array, the view will change.

The above method will directly modify the original array;

But some methods will not replace the original array, but will generate a new array, such as filter(), concat() and slice() .

5.12.6. The role of the key in v-for

When using v-for for list rendering, we usually bind a key attribute to an element or component .

What is the function of this key attribute (written by _Dax1 boss)? Let's take a look at the official explanation first:

  • The key attribute is mainly used in Vue's virtual DOM algorithm to identify VNodes when comparing old and new nodes ;
  • If key is not used , Vue will use an algorithm that minimizes dynamic elements and tries to modify/reuse elements of the same type in place as much as possible;
  • When using key , it will rearrange the order of elements based on the change of key , and will remove/destroy elements whose key does not exist;

The official explanation is too abstract, you can see the explanation linked above.

To put it simply, key can make elements more efficient when adding elements, deleting elements, and rearranging elements through the diff algorithm . In some scenarios, if the key is not added, an error will be reported.

5.13. v-model directive (two-way binding)

A very common function in development when submitting a form is also an important means of interacting with users:

  • For example, the user needs to submit the account password when logging in or registering ;
  • For example, when users retrieve, create, and update information , they need to submit some data;

These all require that we can obtain the data submitted by the user in the code logic, and we usually use the v-model instruction to complete:

  • The v-model directive can create two-way data binding on form input, textarea and select elements ;
  • It will automatically choose the correct method to update the element according to the control type ;
  • Although somewhat magical, v-model is essentially just syntactic sugar , which is responsible for listening to user input events to update data , and performing some special processing in certain extreme scenarios; 
<input type="text" v-model="message">
<h2>{
   
   {message}}</h2>

 When entering into the input box, the text below will also change accordingly.

5.13.1. Principle of v-model 

The official mentioned that the principle of v-model actually has two operations:

  • v-bind binds the value of the value attribute;
  • v-on binds the input event to the function, and the function will get the latest value and assign it to the bound property;

We can use v-bind and v-on to achieve the effect of v-model.

v-model is a grammatical sugar for v-bind and v-on to realize two-way binding.

<div id="app">
    <input type="text" :value="message" @input="inputChange">
    <h2>{
   
   {message}}</h2>
  </div>
  <script src="./vue.js"></script>
  <script>
    //vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          message: "aaaa"
        }
      },
      methods: {
        inputChange(event) {
          this.message = event.target.value
        }
      }
    });
    //将app挂载到id为app的div上
    app.mount("#app");
  </script>

5.13.2.v-model binding textarea

v-model can also bind textarea multi-line text box. Similar to the binding method of input. 

<textarea v-model="message" cols="30" rows="10"></textarea>
<h2>{
   
   {message}}</h2>

5.13.3. v-model binding checkbox

Single checkbox:

  • v-model is a boolean value .
  • At this time, the value attribute of input does not affect the value of v-model.
<div id="app">
    <label for="cb">
      <input type="checkbox" id="cb" v-model="isAgree">同意协议
    </label>
    <h2>{
   
   {isAgree}}</h2>
  </div>
  <script src="./vue.js"></script>
  <script>
    //vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          isAgree: false
        }
      }
    });
    //将app挂载到id为app的div上
    app.mount("#app");
  </script>

 

Multiple checkboxes:

  • When there are multiple check boxes , because multiple check boxes can be selected, the corresponding attribute in data is an array .
  • When one is selected, the value of the input will be added to the array .
<div id="app">
    <label for="basketball">
      <input type="checkbox" id="basketball" value="basketball" v-model="isAgree">篮球
    </label>
    <label for="football">
      <input type="checkbox" id="football" value="football" v-model="isAgree">足球
    </label>
    <label for="badminton">
      <input type="checkbox" id="badminton" value="badminton" v-model="isAgree">羽毛球
    </label>
    <h2>{
   
   {isAgree}}</h2>
  </div>
  <script src="./vue.js"></script>
  <script>
    //vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          isAgree: []
        }
      }
    });
    //将app挂载到id为app的div上
    app.mount("#app");
  </script>

5.13.4. v-model binding radio

Radio can only choose one, the radio button.

<div id="app">
    <label for="male">
      <input type="radio" id="male" value="male" v-model="gender">男
    </label>
    <label for="female">
      <input type="radio" id="female" value="female" v-model="gender">女
    </label>
    <h2>{
   
   {gender}}</h2>
  </div>
  <script src="./vue.js"></script>
  <script>
    //vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          gender: ""
        }
      }
    });
    //将app挂载到id为app的div上
    app.mount("#app");
  </script>

 

5.13.5. v-model binding select

Select is similar to checkbox, and it is also divided into single selection and multiple selection.

Single choice:

  • Only one value can be selected, v-model is bound to a value ;
  • When we select one of the options, its corresponding value will be assigned;
<div id="app">
    <select v-model="choose">
      <option value="choose1">choose1</option>
      <option value="choose2">choose2</option>
      <option value="choose3">choose3</option>
    </select>
    <h2>{
   
   {choose}}</h2>
  </div>
  <script src="./vue.js"></script>
  <script>
    //vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          choose: ""
        }
      }
    });
    //将app挂载到id为app的div上
    app.mount("#app");
  </script>

 

Multiple choice:

  • You can select multiple values ​​v-model is bound to an array ;
  • When multiple values ​​are selected, the value corresponding to the selected option will be added to the array ;

Add multiple and size to the select element to achieve multiple selection.

<select v-model="choose" multiple size="3">
      <option value="choose1">choose1</option>
      <option value="choose2">choose2</option>
      <option value="choose3">choose3</option>
    </select>
    <h2>{
   
   {choose}}</h2>

Hold down ctrl to make multiple selections.

5.13.6. v-model modifier - lazy

In the input case written above, as long as the content is entered in the input box, the bound attribute value will be updated. Sometimes we don't need to respond so quickly in order to optimize performance.

Lazy means lazy. If you add the lazy modifier after v-model, it will be updated when the focus is lost.

<input type="text" v-model.lazy="message">
<h2>{
   
   {message}}</h2>

 

5.13.7. v-model modifier-number

If we want the content entered in the input box to be of type number , we can use the .number modifier .

<input type="text" v-model.number="number">    
<h2>{
   
   {typeof(number)}}</h2>

 

 After vue3, the type of the input element is changed to number , and v-model will automatically convert the type according to the type.

<input type="number" v-model="number">    
<h2>{
   
   {typeof(number)}}</h2>

5.13.8. v-model modifier - trim

If you want to automatically filter whitespace characters entered by the user , you can use the .trim modifier .

<input type="text" v-model.trim="number">    
<h2>{
   
   {number}}</h2>

 Filtering is blank characters before and after filtering , and blank characters between characters will not be filtered.

6. Vue componentization - component development basis

Componentization is the core idea of ​​Vue, React, and Angular, and it is also the focus of our study:

  • Our createApp function passed in an object App , which is actually a component and the root component of our application ;
  • Componentization provides an abstraction that allows us to develop independent and reusable widgets to construct our applications;
  • Any application will be abstracted into a component tree

6.1. Understanding component development

In development, if we put all the processing logic in one page together , the processing will become very complicated , and it is not conducive to subsequent management and expansion ;

But if we split a page into small functional blocks , and each functional block completes its own independent functions , then the management and maintenance of the entire page will become very easy;

If we split the functional blocks one by one, we can build our project like building blocks ;

We need to think about the entire application through the idea of ​​components:

  • We divide a complete page into many components ;
  • Each component is used to implement a functional block of the page ;
  • And each component can be subdivided ;
  • The components themselves can be reused in multiple places .

 Later learn how Vue registers components and how to use the registered components.

6.2. Register global components

Global components need to use our globally created app to register components ;

  1. First write a template template, add id ;
  2. Pass the component name and component object through the component method (the template and the corresponding id need to be written in the object) to register a global component;
  3. Afterwards, we can use this global component directly in the template of the App component .
<div id="app">、
//步骤三
    <cpn-name></cpn-name>
    <cpn-name></cpn-name>
    <cpn-name></cpn-name>
  </div>
//步骤一
  <template id="cpn">
    <h2>template</h2>
  </template>
  <script src="./vue.js"></script>
  <script>
    //vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          message: "aaaa"
        }
      }
    });
    //将app挂载到id为app的div上
//步骤二
    app.component("cpn-name", {
      template: "#cpn"
    })
    app.mount("#app");
  </script>

The component itself also has its own code logic

For example, the component's own data, computed, methods.

app.component("cpn-name", {
      template: "#cpn",
      data() {
        return {
          message: "components data"
        }
      },
      methods: {
        componentMethods() {
          console.log("components methods");
        }
      }
    })

6.3. Component naming

When using app.component to register a component, the first parameter is the name of the component. There are two ways to define the component name:

Method 1: Use kebab-case (dash separator)

  • When defining a component using kebab-case (dash-separated naming) , you must also use kebab-case when referencing this custom element , such as <my-component-name>;
 app.component("my-component-name",{
      template: "#cpn"
    })

Method 2: Use PascalCase (camel case identifier)

  • When defining a component using PascalCase (capitalized names), you can use both nomenclatures when referring to the custom element.
  • That is to say, both <my-component-name> and <MyComponentName> are acceptable ;
 app.component("MyComponentName",{
      template: "#cpn"
    })

6.4. Register local components

Global components are often completed with global components at the beginning of the application, which means that if some components are not used by us, they will also be registered together, and the packaged JavaScript package will be larger:

  • For example, we registered three global components : ComponentA, ComponentB, and ComponentC;
  • In development, we only use ComponentA and ComponentB. If ComponentC is not used but we still register it globally , it means that when packaging tools like webpack package our projects, we will still package them. ;
  • In this way, the final packaged JavaScript package will have the content of ComponentC, and the size of the package will also increase when the user downloads the corresponding JavaScript ;

So in development, we usually use local registration when using components:

  • Partial registration is registered through the components attribute option in the components we need to use ;
  • For example, in the previous App components, we have options such as data, computed, methods, etc. In fact, there can also be a components option ;
  • The components option corresponds to an object , and the key-value pair in the object is the name of the component : component object ;
//vue相关的代码
    const app = Vue.createApp({
      data: function(){
        return {
          message: "aaaa"
        }
      },
      // component属性
      component: {
        // 组件名称: 组件对象
        "MyComponent": {
          template: "#cpn",
          data() {
            return {
              message: "cpn1"
            }
          }
        },
        "MySecondComponent": {
          template: "#cpn2",
          data() {
            return {
              message: "cpn2"
            }
          }
        }
      }
    });
    //将app挂载到id为app的div上
    app.mount("#app");

Of course, the component object in the component object can also be extracted and used as a variable.

6.5. Development mode of Vue

At present, the process of using vue is all in the html file , and we write our own templates, script logic, styles, etc. through the template.

But as the project becomes more and more complex, we will develop in a componentized way:

  • This means that each component will have its own template, script logic, styles, etc .;
  • Of course, we can still extract them into separate js and css files, but they will still be separated ;
  • It also includes that our script is in a global scope, which is prone to naming conflicts ;
  • And our code must use ES5 syntax in order to adapt to some browsers;
  • After we write the code, we still need to build the code through tools ;

So in real development, we can use a single-file component with the suffix .vue to solve it, and we can use webpack or vite or rollup and other construction tools to process it .

6.5.1. Features of single-file components

In this component we can get a lot of features:

  • code highlighting;
  • The modularization capabilities of ES6 and CommonJS;
  • Component-scoped CSS;
  • Preprocessors can be used to build richer components, such as TypeScript, Babel, Less, Sass, etc.;

6.5.2. Method of using single-file component (SFC)

If we want to use the .vue file of this SFC, there are two common ways:

  • Method 1: Use Vue CLI to create a project . The project will help us configure all configuration options by default , and you can directly use the .vue file in it ;
  • Method 2: Use a packaging tool such as webpack, rollup or vite to package it;

 Whether we are doing projects later or developing in the company, we usually use Vue CLI to complete it .

6.5.3. Plug-in recommendations for single-file components (SFCs)

Officially recommend a plug-in: Volar

 If you are using VSCode to develop, it is recommended to use this plug-in, search for volar in the extension, and click to install.

7. Vue componentization - CLI scaffolding 

In real development, we usually use scaffolding to create a project , and the Vue project we use is Vue's scaffolding;

Scaffolding is actually a concept in construction engineering. In our software engineering, some tools that help us build projects are also called scaffolding;

 

Vue's scaffolding is Vue CLI :

CLI is Command-Line Interface, translated as Command Line Interface ;

We can select the configuration of the project and create our project through the CLI;

Vue CLI has built-in webpack-related configuration , we don't need to configure it from scratch;

7.1. Installation of Vue CLI

We can use npm (written by Mr. Shan Miao) to install scaffolding, and we may need to install node first.

If you have used npm before, you can use the command line in the terminal to install scaffolding.

If you use VSCode to develop, the terminal can be created by pressing ctrl+shift+` .

7.1.1. Installing the Vue CLI

We are installing globally (-g stands for global global) , so that we can create projects through vue commands at any time

npm install @vue/cli -g

 The installation was successful (currently the latest version is 5.0.8).

7.1.2. Upgrading the Vue CLI

Older versions can be upgraded with the following command.

npm update @vue/cli -g

7.2. Vue CLI create project

Create a project through the Vue command

Vue create 创建的项目名

 Babel is to convert es6 into es5 syntax; eslint is to check the format of the code. 

Press the blank key on the keyboard to select, the a key to select all, the i key to not select all, and the enter key to go to the next step.

  • Just choose Babel for the time being at the basic stage of learning CLI .

  • Select the 3.x version.

  • Choose to put it in a separate file.
  • The following will ask if you want to set the configuration just now as the default, y/N
  • Enter the name of the preset you want to generate, and start building the project.

This means the creation is complete.

7.3. Vue CLI running project 

  • Go to the project directory and use the npm run serve command to run the project.
cd 项目目录

npm install

npm run serve

  • ctrl+click to open the link and enter the page created by Vue by default.

7.3.1. Project directory structure

 There are many directory structures after the project is created, and the function of each file is shown in the figure.

 

7.4. Coding mode using Vue CLI

After creating the file, it seems that it will not be used anymore. I don’t know how to apply the content I learned before.

  • Write data, computed, component and other attributes directly in the script tag, and then pass this object to export default by default.
<!-- App.vue -->
<template>
  <h2>{
   
   {message}}</h2>
</template>

<script>
 export default {
  data() {
    return {
      message: "message"
    }
  }
}
</script>

<style>

</style> 
  •  Introduce the App.vue file in main.js.
//main.js
import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')

7.5. VSCode quickly generates vue code

In the process of practicing Vue, some code snippets need to be written frequently. We can generate a code snippet in VSCode , which is convenient for us to quickly generate .

The code snippets in VSCode have a fixed format, so we usually use an online tool to complete it.

The specific steps are as follows:

  • The first step is to copy the code that you need to generate a code snippet;
<template>
  <div>AppContent</div>
</template>

<script>
 export default {
  data() {
    return {
      
    }
  }
}
</script>

<style scoped>

</style>
  • In the second step, https://snippet-generator.app/ generates code snippets in the website;

 Copy the content generated on the right.

  • The third step is to configure the code snippet in VSCode;

 Open VSCode, menu bar => file => preferences => user fragment (or configure user code fragment);

 Paste the copied code into it;

 In this way, when entering vue on the vue page, the corresponding code snippet will be generated.

There is too much content to write, and the text is delayed when editing, so I will continue in another article. Vue recognizes the application (2) - The Ultimate Blog - CSDN Blog

Guess you like

Origin blog.csdn.net/m0_51636525/article/details/125729620