Home Web Front-end JS Tutorial How to encapsulate reusable components in vue

How to encapsulate reusable components in vue

Jun 02, 2018 am 10:28 AM
encapsulation use components

Below I will share with you an article about encapsulating reusable components in vue. It has a good reference value and I hope it will be helpful to everyone.

The components encapsulated this time take the toast component as an example

In the past, when using the mobile ui plug-in, through a code such as $.toast('Content to be displayed'), thereby displaying this text on the page and disappearing after a certain period of time.

Now we also try to encapsulate the toast component ourselves.

Preparation work: vue-cli scaffolding project

First take a look at the screenshots of the file directories involved:

The files mainly involved in this encapsulation are Toast.vue toast.js Hello.vue. The main ideas are as follows:

① Toast.vue is the toast component we want to use;

② toast In .js, use Vue.extend() to extend a component constructor, and then instantiate the component constructor to create a reusable component.

Finally, export the function myToast in toast.js. The logic in the function myToast is explained in the code;

③ Call the function in Hello.vue to display the component.

Toast.vue code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

<template>

    <p class="toast" v-if="isShow">

        <p class="toast-p">{{ text }}</p>

    </p>

</template>

<script>

export default{

    data(){

        return {

            text:&#39;内容&#39;,

            isShow:true,

            duration:1500

        }

    }

}

</script>

<style>

*{

    margin: 0;

    padding: 0;

}

.toast{

    position: fixed;

    left: 50%;

 transform: translate(-50%, 0);

 margin-top: 5rem;

 background: #000000;

 line-height: 0.7rem;

    color: #FFFFFF;

    padding: 0 0.2rem;

    border-radius: 0.2rem;

}

</style>

Copy after login

Toast.js code:

1

2

3

4

5

6

7

8

9

10

11

import Vue from &#39;vue&#39;;

import Toast from &#39;@/components/Toast&#39;; //引入组件

let ToastConstructor = Vue.extend(Toast) // 返回一个“扩展实例构造器”

  

let myToast = ()=>{

 let toastDom = new ToastConstructor({

 el:document.createElement(&#39;p&#39;) //将toast组件挂载到新创建的p上

 })

 document.body.appendChild( toastDom.$el ) //把toast组件的dom添加到body里

}

export default myToast;

Copy after login

Hello.vue code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

<template>

 <p class="hello">

 <button @click="showToast">按钮</button>

 </p>

</template>

<script>

import Vue from &#39;vue&#39;;

import toast from &#39;./js/toast&#39;; //引入toast函数

Vue.prototype.$toast = toast;  //给Vue对象添加$toast方法

export default {

 name: &#39;hello&#39;,

 data () {

 return {

  

 }

 },

 methods:{

    showToast(){

        this.$toast();  //现在就可以调用了

    }

 }

}

</script>

Copy after login

Through the above steps, there is still a difference between the real toast effect. The effect we want to achieve is to make the displayed content disappear after a period of time. Then, we have to modify it from toast.js. You have to rewrite the myToast function and set two incoming parameters for it, one is the displayed content, and the other is the displayed time.

The modified code of toast.js is as follows:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

import Vue from &#39;vue&#39;;

import Toast from &#39;@/components/Toast&#39;; //引入组件

let ToastConstructor = Vue.extend(Toast) // 返回一个“扩展实例构造器”

  

let myToast = (text,duration)=>{

 let toastDom = new ToastConstructor({

 el:document.createElement(&#39;p&#39;) //将toast组件挂载到新创建的p上

 })

 document.body.appendChild( toastDom.$el ) //把toast组件的dom添加到body里

  

 toastDom.text = text;

 toastDom.duration = duration;

  

 // 在指定 duration 之后让 toast消失

 setTimeout(()=>{

 toastDom.isShow = false;

 }, toastDom.duration);

}

export default myToast;

Copy after login

Then, when we call it in Hello.vue, it should look like this: this.$toast('New content', 2000);Our group toast component can be used normally!

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

Related articles:

Data grouping example of v-for in Vue

Use v-for in vue to traverse a two-dimensional array Method

Use import and require in JavaScript to package and implement principle analysis

The above is the detailed content of How to encapsulate reusable components in vue. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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

How to implement calendar component using Vue? How to implement calendar component using Vue? Jun 25, 2023 pm 01:28 PM

Vue is a very popular front-end framework. It provides many tools and functions, such as componentization, data binding, event handling, etc., which can help developers build efficient, flexible and easy-to-maintain Web applications. In this article, I will introduce how to implement a calendar component using Vue. 1. Requirements analysis First, we need to analyze the requirements of this calendar component. A basic calendar should have the following functions: display the calendar page of the current month; support switching to the previous month or next month; support clicking on a certain day,

Which computer should Geographic Information Science majors choose? Which computer should Geographic Information Science majors choose? Jan 13, 2024 am 08:00 AM

Recommended computers suitable for students majoring in geographic information science 1. Recommendation 2. Students majoring in geographic information science need to process large amounts of geographic data and conduct complex geographic information analysis, so they need a computer with strong performance. A computer with high configuration can provide faster processing speed and larger storage space, and can better meet professional needs. 3. It is recommended to choose a computer equipped with a high-performance processor and large-capacity memory, which can improve the efficiency of data processing and analysis. In addition, choosing a computer with larger storage space and a high-resolution display can better display geographic data and results. In addition, considering that students majoring in geographic information science may need to develop and program geographic information system (GIS) software, choose a computer with better graphics processing support.

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

TrendForce: Nvidia's Blackwell platform products drive TSMC's CoWoS production capacity to increase by 150% this year TrendForce: Nvidia's Blackwell platform products drive TSMC's CoWoS production capacity to increase by 150% this year Apr 17, 2024 pm 08:00 PM

According to news from this site on April 17, TrendForce recently released a report, believing that demand for Nvidia's new Blackwell platform products is bullish, and is expected to drive TSMC's total CoWoS packaging production capacity to increase by more than 150% in 2024. NVIDIA Blackwell's new platform products include B-series GPUs and GB200 accelerator cards integrating NVIDIA's own GraceArm CPU. TrendForce confirms that the supply chain is currently very optimistic about GB200. It is estimated that shipments in 2025 are expected to exceed one million units, accounting for 40-50% of Nvidia's high-end GPUs. Nvidia plans to deliver products such as GB200 and B100 in the second half of the year, but upstream wafer packaging must further adopt more complex products.

AMD 'Strix Halo” FP11 package size exposed: equivalent to Intel LGA1700, 60% larger than Phoenix AMD 'Strix Halo” FP11 package size exposed: equivalent to Intel LGA1700, 60% larger than Phoenix Jul 18, 2024 am 02:04 AM

This website reported on July 9 that the AMD Zen5 architecture "Strix" series processors will have two packaging solutions. The smaller StrixPoint will use the FP8 package, while the StrixHalo will use the FP11 package. Source: videocardz source @Olrak29_ The latest revelation is that StrixHalo’s FP11 package size is 37.5mm*45mm (1687 square millimeters), which is the same as the LGA-1700 package size of Intel’s AlderLake and RaptorLake CPUs. AMD’s latest Phoenix APU uses an FP8 packaging solution with a size of 25*40mm, which means that StrixHalo’s F

Vue component practice: paging component development Vue component practice: paging component development Nov 24, 2023 am 08:56 AM

Vue component practice: Introduction to paging component development In web applications, the paging function is an essential component. A good paging component should be simple and clear in presentation, rich in functions, and easy to integrate and use. In this article, we will introduce how to use the Vue.js framework to develop a highly customizable paging component. We will explain in detail how to develop using Vue components through code examples. Technology stack Vue.js2.xJavaScript (ES6) HTML5 and CSS3 development environment

See all articles