Simple steps to encapsulate components in Vue projects

Simple steps to encapsulate components in Vue projects

Preface

As the business develops, functional development can no longer meet our needs for the front end. This article mainly shows you how to develop your own component library.

Usage scenarios: Development of internal component libraries, development of personal component libraries, decoupling from projects, using the same component in multiple projects, and only needing to maintain one set of component libraries

How to encapsulate a Toast component

Component Description:

Implement the prompt function.

Effect display:

Functions implemented:

  • A pop-up window will pop up based on a certain judgment condition or by clicking a button;
  • Configurable position, type, style name, etc.

Use Cases

1. Easy to use

vm.$toast('Network abnormality!')

2. Use the options parameter

* message: prompt information content* duration: dwell time, in milliseconds* position: display position: top, middle, bottom
* className style name vm.$toast({
    message: 'Network abnormality! ',
    duration: 2000,
    position: 'middle',
    className: 'big'
})

3. Error message

vm.$toast({
    message: 'Verification code error! ',
    duration: 2000,
    type: 'error'
})

Specific implementation

First toast.vue

<template>
    <transition name="toast-pop">
        <div v-show="visible" class="toast" :class="customClass" @click="handleClose">
            <span class="text">{{message}}</span>
        </div>
    </transition>
</template>

<script>
    export default {
        name: 'Toast',
        props: {
            message: String, // prompt information content className: { // style name type: String,
                default: ''
            },
            position: { // Position: top, middle, bottom
                type: String,
                default: 'middle'
            },
            type: { // Prompt type: normal, error
                type: String,
                default: 'normal'
            }
        },
        data () {
            return {
                // Whether to display visible: false
            }
        },
        computed: {
            // Get style customClass () {
                let classes = []
                classes.push('toast-' + this.type)
                switch (this.positon) {
                    case 'top':
                        classes.push('is-placetop')
                        break
                    case 'bottom':
                        classes.push('is-placebottom')
                        break
                    default:
                        classes.push('is-placemiddle')
                }
                this.className && classes.push(this.className)
                Return classes
            }
        },
        methods: {
            handleClose () {
                this.$emit('close')
            }
        }
    }

</script>

<style lang="scss" scoped px2rem="false">
    .toast {
        position: fixed;
        box-sizing: border-box;
        min-width: 200px;
        max-width: 50%;
        max-height: 85%;
        margin-top: 0;
        padding: 18px 30px;
        border-radius: 10px;
        background: rgba(0, 0, 0, 0.7);
        color: #fff;
        text-align: center;
        overflow-y: auto;
        z-index: 2000;
        .text {
            display: block;
            font-size: 16px;
            line-height: 1.5;
            text-align: center;
            word-wrap: break-word;
        }
    }

    .is-placetop {
        top: 50px;
        left: 50%;
        transform: translate(-50%, 0);
    }
    .is-placemiddle {
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }
    .is-placebottom {
        bottom: 50px;
        left: 50%;
        transform: translate(-50%, 0);
    }
    .is-placetop.toast-pop-enter-active, .is-placetop.toast-pop-leave-active,
    .is-placemiddle.toast-pop-enter-active, .is-placemiddle.toast-pop-leave-active {
        transition: opacity .3s linear, margin-top .3s ease;
    }

    .is-placetop.toast-pop-enter, .is-placetop.toast-pop-leave-to,
    .is-placemiddle.toast-pop-enter, .is-placemiddle.toast-pop-leave-to {
        margin-top: 30px;
        opacity: 0;
    }
    .is-placebottom.toast-pop-enter-active, .is-placebottom.toast-pop-leave-active {
        transition: opacity .3s linear, margin-bottom .3s ease;
    }

    .is-placebottom.toast-pop-enter, .is-placebottom.toast-pop-leave-to {
        margin-bottom: -30px;
        opacity: 0;
    }
    .toast-error {
        background: rgba(255,102,104,.9);
    }
</style>

toastPlugin.js

import Vue from 'vue'
import Toast from './toast.vue'

// toast constructor const ToastConstructor = Vue.extend({
    extends: Toast
})

// toast instance pool let toastPool = []

/** Get toast instance (if there is one in the instance pool, take it from the pool, if there is none, create a new one) */
let getInstance = () => {
    // console.log('toastPool:', toastPool)
    if (toastPool.length > 0) {
        return toastPool.shift()
    }
    return new ToastConstructor({
        el: document.createElement('div')
    })
}

/** Return the instance to the instance pool */
let returnInstance = instance => {
    if (instance) {
        toastPool.push(instance)
        // console.log('Return instance:', instance, toastPool)
    }
}

/** Remove toast's DOM node from the document*/
function removeDom (event) {
    if (event.target.parentNode) {
        event.target.parentNode.removeChild(event.target)
    }
}

// Close ToastConstructor.prototype.close = function () {
    this.visible = false // Invisible this.closed = true // Closed state this.$el.addEventListener('transitionend', removeDom) // Remove the DOM node after the animation is completed returnInstance(this) // The instance object is returned to the instance pool and the instance can be reused }

// Display toast prompt information export default function (options = {}) {
    // Display time, default is 3 seconds let duration = options.duration || 3000
    let instance = getInstance()
    // console.log('instance=', instance)
    // Display type instance.type = options.type || 'normal'
    // Display content instance.message = typeof options === 'string' ? options : options.message
    // Display position: top, middle, bottom
    instance.position = options.position || 'middle'
    instance.className = options.className || ''
    // Remove the animation completion eventinstance.$el.removeEventListener('transitionend', removeDom)
    instance.$on('close', () => {
        instance.close()
    })
    // console.log('instance.$el=', instance.$el)
    // Add the node to the document document.body.appendChild(instance.$el)
    instance.visible = true
    instance.closed = false

    // Clear the timer instance.timer && clearTimeout(instance.timer)
    // Set the timer and close the toast
    instance.timer = setTimeout(() => {
        // console.log('close', instance)
        !instance.closed && instance.close()
        instance.timer = null
    }, duration)
}

main.js

import ToastPlugin from './plugins/toastPlugin.js'

// toast prompt information plug-in Vue.use(ToastPlugin)

Summarize

This is the end of this article about encapsulating components in Vue projects. For more relevant Vue project encapsulation components content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Implementation of regionalization and component encapsulation of Vuejs pages
  • Vue2.0 custom component method (encapsulation of Vue components)
  • Basic steps of Vue encapsulation component js version

<<:  How to install and deploy MySQL 8.0 under CentOS8

>>:  Example of implementing load balancing with Nginx+SpringBoot

Recommend

Detailed explanation of Grid layout and Flex layout of display in CSS3

Gird layout has some similarities with Flex layou...

Detailed explanation of CSS float property

1. What is floating? Floating, as the name sugges...

Introduction to building a DNS server under centos7

Table of contents 1. Project environment: 2: DNS ...

How to avoid duplication of data when inserting in MySql batch

Table of contents Preface 1. insert ignore into 2...

Summary of 7 reasons why Docker is not suitable for deploying databases

Docker has been very popular in the past two year...

HTML web page creation tutorial Use iframe tags carefully

Using iframes can easily call pages from other we...

MySQL sorting principles and case analysis

Preface Sorting is a basic function in databases,...

JS realizes the calculation of the total price of goods in the shopping cart

JS calculates the total price of goods in the sho...

WeChat applet custom menu navigation to achieve staircase effect

Design Intentions When developing a page, you oft...

MySQL 8.0.12 winx64 detailed installation tutorial

This article shares the installation tutorial of ...

About Tomcat combined with Atomikos to implement JTA

Recently, the project switched the environment an...

Implementation of MySQL multi-version concurrency control MVCC

Transaction isolation level settings set global t...