Implement a simple Toast plug-in, easy to migrate to different projects, used for global prompt, warning some information.
Overview: In the front-end project, sometimes it is necessary to inform and prompt some information to the user, especially in the background system, whether the operation is correct or not, it is necessary to give the user some information.
Example 1.
Within the Methods of the Vue component, call the following code
this.$toast({
content: "Self-closing".autoClose: true
})
Copy the code
A Toast pop-up box will appear on the right side of the page. When clicked for many times, it will be displayed in sequence and Toast can be automatically closed. The specific effect is shown in the figure below.
Github UI-Library
Principle 2.
-
The code structure
The Toast plug-in is divided into two parts:
- The Toast component itself contains its OWN DOM structure as well
data
, and complete the mount and destruction in the page during its life cycle; - Build a layer of proxies outside the component and provide methods to invoke and control the order in which multiple toasts are displayed on the page.
- The Toast component itself contains its OWN DOM structure as well
-
Toast method
To be able to pass this.$toast({… }) to call the Toast component, add a method to Vue’s Prototype as follows
let instances = [] let initIndex = 0 Vue.prototype.$toast = (options = {}) = > { /* Create an instance of the Toast component */ let instance = generateInstance(options) /* Store a single toast in the queue */ instances.push(instance) } Copy the code
When this method is called, an instance of the Toast component is created through generateInstance and put into an Instances for unified management.
/* Construct a single toast */ const ToastConstructor = Vue.extend(Toast) const verticalOffset = 16 function generateInstance(options) { // Create an instance of Toast using ToastConstructor let instance = new ToastConstructor({ propsData: options }).$mount(document.createElement('div')) if (typeof options.onClose === 'function') instance.onClose = options.onClose // Calculate instance verticalOffset let id = 'toast_' + initIndex++ instance.id = id // Initializes the vertical offset of Toast in space instance.verticalOffset = initVerticalOffset(instance.position) // Listen on the component close instance.$once('toastClose'.function () { const curInstance = this // Recalculate the vertical offset when the Toast component is closed updateVerticalOffset(curInstance) typeof curInstance.onClose === 'function' && curInstance.onClose() }) return instance; } Copy the code
In the generateInstance function, we first create an instance of the Toast component using the ToastConstructor constructor and pass in property values via propsData, Render the component with $mount(document.createElement(‘div’)).
ToastConstructor is a constructor that creates the Toast component through vue.extend. For details on how this works, see the general solution for creating forms based on the Vue constructor.
The initVerticalOffset function calculates the initial offset of the Toast component
/* Initializes the vertical properties of each toast object on the page */ function initVerticalOffset(position) { // Filter Toast components in the same direction let typeInstances = instances.filter(item= > item.position === position) // Calculate the offset return typeInstances.reduce((sum, elem) = > (elem.$el.offsetHeight + sum + verticalOffset), verticalOffset) } Copy the code
Later, when a Toast is closed, the offsets of all Toast instances on the page need to be updated
/* Update the vertical properties of each toast object on the page */ function updateVerticalOffset(removeInstance) { let index = 0 let removeHeight = removeInstance.verticalOffset // Compatible with IE remove find method for (; index < instances.length; index++) { if (instances[index].id === removeInstance.id) break; } instances.splice(index, 1); // Delete the closed Toast component instances.splice(index, 1) // Update the location of the component after the deleted location for (; index < instances.length; ++index) { if (instances[index].position === removeInstance.position) { [instances[index].verticalOffset, removeHeight] = [removeHeight, instances[index].verticalOffset] } } } Copy the code
This completes the creation of the Toast component, how to initialize it in the page, and where to update it.
-
Toast components
The functions of the components are relatively simple. They only need to display information and have two functions of automatic closing and manual closing. Their properties also include the type, location and content of Toast.
- Component life cycle
let instance = new ToastConstructor({ propsData: options }).$mount(document.createElement('div')) Copy the code
Mounted’s life cycle is triggered when the Toast component $mount is called
mounted() { // Mount Toast in the page document.body.appendChild(this.$el); // Call startTimer when automatic shutdown is required if (this.autoClose) this.startTimer(); }, beforeDestroy() { this.stopTimer(); this.$el.removeEventListener("transitionend".this.destroyElement); }, destroyed() { / / logout this.$el.parentNode.removeChild(this.$el); } Copy the code
- Auto – off When you need auto – off, make use of it
setTimeout
Complete this feature and log outclearTimeout
Drop to prevent leakage.
startTimer() { if (this.duration > 0) { this.timer = setTimeout((a)= > { if (!this.closed) { this.close(); }},this.duration); } }, stopTimer() { if (this.timer) clearTimeout(this.timer); } Copy the code
Use 3.
Further encapsulate it as a plug-in for Vue
export default {
install (Vue) {
Vue.prototype.$toast = (options = {}) = >{... }}}Copy the code
And for the required attributes that need to be passed in, do processing exception handling
let requireProps = Object.keys(Toast.props)
.filter((elem) = > (Toast.props[elem].required))
requireProps.forEach((elem) = > {
if(! options[elem])throw `err: options lack ${elem} prop`
})
if( options.type && ! types.some(elem= > elem === options.type) )
throw `err: toast not exist ${options.type} type`
Copy the code
4. To summarize
Reduce business workload by encapsulating a Toast plug-in to extract common parts between different businesses.
Previous articles:
- Component library for Vue from zero (zero) – basic structure and build tools
- From zero implementation Vue component library (I) – Toast implementation
- Implementation from zero Vue component library (ii) – Slider implementation
- From zero Vue component library (iii) – Tabs implementation
- Vue component library from zero (four) – file-reader implementation
- Vue component library from zero (v) – Breadcrumb implementation
- From zero to implement Vue component library (vi) – hover-tip implementation
- Vue component library from zero (7) – message-box implementation
- Implement Vue from zero component library (eight) – Input implementation
- Implement Vue component library from zero (9) – InputNumber implementation
- Implement Vue from zero component library (x) – Select implementation
- Implement Vue component library from zero (eleven) – date-picker implementation
- Vue component library from zero implementation (twelve) – Table implementation
- Implement Vue from zero component library (xiII) – Pagination implementation
- Implement Vue from zero component library (xiv) – RadioGroup implementation
- Implement Vue from zero component library (XV) – CheckboxGroup implementation
Original statement: This article is an original article, please indicate the source.