Home Web Front-end JS Tutorial Detailed explanation of vue components and reuse

Detailed explanation of vue components and reuse

May 26, 2018 am 09:46 AM
Reuse components Detailed explanation

Component (Component) is one of the most powerful features of Vue.js. Components can extend HTML elements, encapsulating reusable code. This article mainly introduces vue components and reuse. Friends in need can refer to

1. What is a component

Component (Component ) is one of the most powerful features of Vue.js. Components can extend HTML elements, encapsulating reusable code.

2. Component usage

Components need to be registered before they can be used. There are two ways of registration: global registration and local registration.

2.1 After global registration, any V ue instance can be used. For example:      

 <p id="app1">
      <my-component></my-component>
    </p>
Vue.component(&#39;my-component&#39;,{
  template: &#39;<p>这里是组件的内容</p>&#39;
});
var app1 = new Vue({
  el: &#39;#app1&#39;
});
Copy after login

To use this component in the parent instance, you must register it before the instance is created, and then you can use

The DOM structure of the template must be contained by an element. If it is written directly as "here is the content of the component" without "

" It cannot be rendered. (And the outermost layer can only have one root

tag)

2.2 In a Vue instance, you can use the component option to register a component locally. The registered component is only valid within the scope of the instance. For example:

    <p id="app2">
      <my-component1></my-component1>
    </p>
var app2 = new Vue({
  el: &#39;#app2&#39;,
  components:{
   &#39;my-component1&#39;: {
     template: &#39;<p>这里是局部注册组件的内容</p>&#39;
   }
  }
});
Copy after login

2.3 data must be a function

In addition to the template option, other options can also be used in the component like a Vue instance. Such as data, computed, methods, etc. But when using data, it is slightly different from the example. data must be a function, and then the data is returned.

    <p id="app3">
      <my-component3></my-component3>
    </p>
Vue.component(&#39;my-component3&#39;,{
  template: &#39;<p>{{message}}</p>&#39;,
  data: function(){
    return {
      message: &#39;组件内容&#39;
    }
  }
});
var app3 = new Vue({
  el: &#39;#app3&#39;
});
Copy after login

Generally, the returned object should not refer to an external object, because if the returned object refers to an external object, then this object is shared, and any Any modifications made by one party will be synchronized.

So generally a new independent data object is returned to the component.

Supplement: vue-router component reuse issue

The component system is an important part of Vue, it can combine a complex page The abstraction is decomposed into many small, independent, reusable components, and the application is composed by combining the components. Combined with the routing function of vue-router, each component is mapped to the corresponding route, and the changes in the routing are used to tell Vue where to render. They implement jump navigation between various components and pages.

Problem

When using vue-router to switch routes, it will trigger the update of the component tree and render a new component tree according to the defined route. The general switching process is as follows of:

- Deactivate and remove unnecessary components
- Verify the feasibility of switching
- Reuse components that have not been updated
- Enable and activate new components

For specific route switching control process, please refer to the official document: Switching Control Pipeline

How does vue-router determine that a certain component can be reused? Let’s take a look at the following routing configuration:

{
  path: &#39;post/:postId&#39;,
  name: &#39;post&#39;,
  component: resolve => require([&#39;./components/Post.vue&#39;],resolve)
}
Copy after login

This is the route that loads the corresponding article page through the article ID. When accessing for the first time, Post.vue The component will be rendered into the component tree. When the mounted component is installed, the article content is obtained through the article ID and displayed on the page. When we access another article, the routing parameter: postId changes. According to our expectations, the new article should be displayed. content, but it backfired.

What we see is still the previous article. Although the routing parameters have changed, vue-router will think that you are accessing the Post.vue component. Since the component has been rendered before, it will be copied directly. Use the previous component and will not perform any operations in the component including life cycle functions such as mounted.

So what we finally see is the content of the original component.

So how can we achieve the desired effect? An effective solution is introduced below

Solution

We can use the watch listener to monitor routing changes. According to the routing The parameters change to respond to the corresponding data. The specific implementation process is as follows:

Define the data acquisition method

First define a method to obtain articles, and obtain the corresponding article information from the background according to the article ID .

methods: {
  getPost(postId) {
    this.$http.get(`/post/get_post/${postId}`).then((response) => {
      if(response.data.code === 0){
        this.post = response.data.post;
      }
    });
  }
}
Copy after login

Listen to the route

The next step is to determine whether the target component is a Post.vue component when the route is switched. This can be implemented based on the defined routing name name. If so, we can get the target article ID from the routing information to update the component content.

watch: {
  &#39;$route&#39; (to, from) {
    if(to.name === &#39;post&#39;){
      this.getPost(to.params.postId);
    }
  }
}
Copy after login

Component initialization

What needs to be noted here is that when the component is mounted to the component tree for the first time , the monitoring of routing is invalid. At this time, we need to initialize the component in the life cycle hook mounted:

mounted() {
  this.getPost(this.$route.params.postId);
}
Copy after login

Write at the end

Through the above method, the component content can be updated as the routing parameters change, which effectively solves the problem of invalid routing parameters caused by the reuse of vue-router components.

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

JavaScript generates a time list within a specified range

Detailed explanation of parameters based on webpack.config.js

nodejs method to implement file upload based on express

##

The above is the detailed content of Detailed explanation of vue components and reuse. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to install the Windows 10 old version component DirectPlay How to install the Windows 10 old version component DirectPlay Dec 28, 2023 pm 03:43 PM

Many users always encounter some problems when playing some games on win10, such as screen freezes and blurred screens. At this time, we can solve the problem by turning on the directplay function, and the operation method of the function is also Very simple. How to install directplay, the old component of win10 1. Enter "Control Panel" in the search box and open it 2. Select large icons as the viewing method 3. Find "Programs and Features" 4. Click on the left to enable or turn off win functions 5. Select the old version here Just check the box

Detailed explanation of obtaining administrator rights in Win11 Detailed explanation of obtaining administrator rights in Win11 Mar 08, 2024 pm 03:06 PM

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in Oracle SQL Detailed explanation of division operation in Oracle SQL Mar 10, 2024 am 09:51 AM

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

Angular components and their display properties: understanding non-block default values Angular components and their display properties: understanding non-block default values Mar 15, 2024 pm 04:51 PM

The default display behavior for components in the Angular framework is not for block-level elements. This design choice promotes encapsulation of component styles and encourages developers to consciously define how each component is displayed. By explicitly setting the CSS property display, the display of Angular components can be fully controlled to achieve the desired layout and responsiveness.

How to open the settings of the old version of win10 components How to open the settings of the old version of win10 components Dec 22, 2023 am 08:45 AM

Win10 old version components need to be turned on by users themselves in the settings, because many components are usually closed by default. First we need to enter the settings. The operation is very simple. Just follow the steps below. Where are the win10 old version components? Open 1. Click Start, then click "Win System" 2. Click to enter the Control Panel 3. Then click the program below 4. Click "Enable or turn off Win functions" 5. Here you can choose what you want to open

Detailed explanation of the role and usage of PHP modulo operator Detailed explanation of the role and usage of PHP modulo operator Mar 19, 2024 pm 04:33 PM

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

Detailed explanation of the linux system call system() function Detailed explanation of the linux system call system() function Feb 22, 2024 pm 08:21 PM

Detailed explanation of Linux system call system() function System call is a very important part of the Linux operating system. It provides a way to interact with the system kernel. Among them, the system() function is one of the commonly used system call functions. This article will introduce the use of the system() function in detail and provide corresponding code examples. Basic Concepts of System Calls System calls are a way for user programs to interact with the operating system kernel. User programs request the operating system by calling system call functions

Detailed explanation of Linux curl command Detailed explanation of Linux curl command Feb 21, 2024 pm 10:33 PM

Detailed explanation of Linux's curl command Summary: curl is a powerful command line tool used for data communication with the server. This article will introduce the basic usage of the curl command and provide actual code examples to help readers better understand and apply the command. 1. What is curl? curl is a command line tool used to send and receive various network requests. It supports multiple protocols, such as HTTP, FTP, TELNET, etc., and provides rich functions, such as file upload, file download, data transmission, proxy

See all articles