Components are dynamically inserted and exited

demand

Real-time alarm: Receives real-time alarm information from the server using the WebSocket protocol. When the real-time alarm information is moved down on the page, it disappears immediately. The system automatically exits after being displayed for one minute. Pop-up Windows for real-time alarm information are added one by one. The one that pops up first moves down, and the latest one is at the top. Only the latest three real-time alarms are displayed on the page

Use the standalone component approach

Write the alarm popup component

<! --alarm-dialog.vue -->
<template>
    <div class='alarm-realtime' :id="`rt${alarmItem.id}`" :style="{top: topCount}">
        <div class='alarmItem' :class="showDialog ? 'show' : 'disppear'">.</div>
    </div>
</template>
Copy the code

TopCount is calculated according to the index of this data in the alarmList array, and moves down or up according to the position relationship in the array.

// alarm-dialog.vue
export default {
    data () {
        return {
            topCount: '72px'
        };
    },
    computed: {
        dialogIndex () {
            const index = this.$store.state.alarmIdList.findIndex(item= > item === this.alarmItem.id);
            return index;
        },
        showDialog () {
            const id = this.$store.state.alarmIdList.find(item= > item === this.alarmItem.id);
            return!!!!! id; }},watch: {
    	// Adjust topCount according to dialogIndex changes
        dialogIndex () {
            const top = this.dialogIndex * 116;
            this.topCount = 72 + top + 'px';
        }
    },
    mounted () {
        const top = this.dialogIndex * 116;
        this.topCount = 72 + top + 'px'; }}Copy the code

Make this component a stand-alone component with vue.extend ().

// alarm-dialog.js
import Vue from 'vue'
import AlarmDialog from './alarm-dialog.vue'
import Store from '@store'

const AlarmConstructore = Vue.extend(AlarmDialog)
/ / injection vuex
AlarmConstructore.prototype.$store = Store

function showAlarmDialog (alarmItem) {
	// Every time a popover opens, insert its ID into the alarmIdList array, default to display
	Store.commit('changeAlarmIdList', {
        id: alarmItem.id,
        show: true
    });
    const dialogDom = new AlarmContructore({
        el: document.createElement('div'),
        data () {
            return {alarmItem}
        }
    })
    document.body.appendChild(dialogDom.$el);
}

function registryAlarm () {
    Vue.prototype.$alarm = showAlarmDialog;
}

export default registryAlarm;
Copy the code

The method of vuex

state: { alarmIdList: [] }, mutations: {{changeAlarmIdList (state, data) if (data. Show) {/ / each display element from an array state. The head alarmIdList. Unshift (data. Id); } else {state.alarMIDList = state.alarmidList. Filter (item => item! == data.id); }}}Copy the code

Register in main.js

import registryAlarm from '@views/alarm-dialog'
Vue.use(registryAlarm)
Copy the code

use

// index.js
linkSocketIo () {
    ...
    socketio.on('ALARM_EVENT'.(data) = > {
        const result = JSON.parse(data);
        // An alarm pop-up window is displayed
        this.$alarm(result);
        // If the alarmIdList has more than three elements, delete it
        if (this.alarmIdList.length > 3) {
            this.removeAlarmDialog();
        }
        // Set the timer
        this.controlTimer();
    });
},
removeAlarmDialog () {
    // Delete the last popover
    const id = this.alarmIdList.pop();
    this.changeAlarmIdList({ show: false, id });
    const el = document.getElementById(`rt${id}`);
    // Give some time to display the disappearing animation
    setTimeout(() = > {
        el.remove();
    }, 300);
},
controlTimer () {
    if (this.alarmIdList.length === 0) {
        return false;
    }
    // Exit automatically after one minute
    const timer = setTimeout(() = > {
        this.removeAlarmDialog();
    }, 60000);
    this.timerList.unshift(timer);
    // If there are more than three elements, the timer array is also deleted
    if (this.timerList.length > 3) {
        const timer = this.timerList.pop();
        clearTimeout(timer); }}Copy the code

The effect is as follows:

Dynamically loading images

demand

There are two groups of images, one for historical alarms and one for real-time alarms. Each group has 10 pictures, showing different images according to the type.

Using the require. The context

Save the images in the same folder and name them with the suffix -history for historical alarm images and -realTime for real-time alarm images.

methods: {
    handleImages () {
    	// Place the image in the alarm folder
        const routeImgs = require.context('@assets/images/alarm'.false./\.png$/);
        const nameList = routeImgs.keys();
        nameList = nameList.filter(item= > {
            If this. Realtime is true, it is a real-time alarm
            if (this.realtime) {
                return item.indexOf('-realtime')! = = -1;
            } else {
                return item.indexOf('-history')! = = -1; }}); nameList.forEach(item= > {
        	/ / item for. / car - realtime. PNG
            const reg = /\.\/(.+)\.png/;
            const name = item.replace('. '.' ');
            / / fileName for the car
            const fileName = reg.exec(item)[1].split(The '-') [0];
            this.$set(this.routeImgs, fileName, routeImgs(item)); }); }}Copy the code

Component dynamic switching

demand

When switching between components, keep them in state to avoid performance problems caused by repeated rerendering.

Keep alive and component

Dynamic switching between components can be done by adding a special IS attribute to the < Component > element of the Vue.

<! -- Components change when 'currentTabComponent' changes --> <component v-bind:is="currentTabComponent"></component>Copy the code

But Vue creates a new currentTabComponent instance each time a new label is toggled. It is desirable that component instances of those tags be cached when they are first created. Its dynamic components can be wrapped with a

element.

<! -- Deactivated components will be cached! --> <keep-alive> <component v-bind:is="currentTabComponent"></component> </keep-alive>Copy the code

At the end

For more articles, please go to Github, if you like, please click star, which is also a kind of encouragement to the author.