Home Web Front-end JS Tutorial How to implement vue component reuse in actual projects

How to implement vue component reuse in actual projects

Jun 09, 2018 pm 03:40 PM

This time I will bring you how to implement vue component reuse in actual projects. What are the precautions for how to implement vue component reuse in actual projects? The following is a practical case, let's take a look.

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('my-component',{
  template: '<p>这里是组件的内容</p>'
});
var app1 = new Vue({
  el: '#app1'
});
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 component in the form of

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

". (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: '#app2',
  components:{
   'my-component1': {
     template: '<p>这里是局部注册组件的内容</p>'
   }
  }
});
Copy after login

2.3 data must be a function

In addition to the template option, components can also use other options like Vue instances, 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('my-component3',{
  template: '<p>{{message}}</p>',
  data: function(){
    return {
      message: '组件内容'
    }
  }
});
var app3 = new Vue({
  el: '#app3'
});
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 modifications by either 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: 'post/:postId',
  name: 'post',
  component: resolve => require(['./components/Post.vue'],resolve)
}
Copy after login

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

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

Listening route

接着是在路由切换的时候判断目标组件是否是Post.vue组件,这里可以根据定义的路由名称name实现,如果是,我们就可以从路由信息中获取目标文章ID来更新组件内容。

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

组件初始化

这里需要注意的是,当组件首次被挂载到组件树上时,对路由的监听是无效的,这时我们需要在生命周期钩子mounted对组件进行初始化工作:

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

写在最后

通过上面的方法就可以实现组件内容随路由参数的变化而更新了,有效解决了vue-router组件复用导致路由参数失效的问题。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

vue项目中watch的immediate使用

create-react-app配置eslint步骤详解

The above is the detailed content of How to implement vue component reuse in actual projects. 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)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles