Components are an extremely important concept in Vue. The Toast component is also used frequently in mobile web development. This article takes the Toast component as an example to explain some knowledge points of the Vue component.
1. Single-file components
During daily development, our project folders are usually created using vue-CLI to organize code as a single file component. Following the usual development process, now create a toast.vue file.
We started to look at some of the key points of implementing the Toast component:
- This component has two prop: Visible and MSG. Visible controls show and hide, MSG is what is displayed
- Position of the component: To determine the position relative to the screen viewport, set position to Fixed and set the Z-index value to a higher value. To center the element, the Translate attribute is used
- This component is animated when shown or hidden: Use the Transition component for the transition effect
Based on the above analysis, the code now looks like this.
<template>
<transition name="toast-bounce">
<div class="toast" v-show="visible">
<p class="toast-msg">{{ msg }}</p>
</div>
</transition>
</template>
<script>
export default {
name: 'Toast'.props: {
visible: {
type: Boolean.required: true
},
msg: {
type: String.required: true}}}</script>
<style lang="scss" scoped>Animating: 0; // Animating: 0; // Animating: 0; } .toast { box-sizing: border-box; position: fixed; max-width: 80%; left: 50%; top: 50%; padding: 20px; z-index: 99; transition: all .3s ease; transform: translate(-50%, -50%); border-radius: 10px; Background: RGBA (0, 0, 0, 0.7); color: #fff; text-align: center; .toast-msg { text-align: center; }}</style>Copy the code
Introduce the Toast component on the page that needs it, register it, and use it.
2. How do I manually create a component
Introduced as a single file component, there are several inconveniences.
- Toast is imported every time it is used
- The parent component’s state should contain a visible property (assuming we’re not using mixins)
- After setting visible to true for the parent component, use a timer to set Visible to false
For frequently used components like this, the easiest way to create, mount, and destroy them is by calling a function. However, during the development of the project, we focused on the implementation of the components and ignored some of these actions. Next we’ll show you how to manually create the Toast component, attach it to document.body, display it for a while, destroy the component, and remove the element.
Component creation and mounting
The script tag of a Vue single file simply exports an object containing component options. To create the component, a constructor is obtained using vue.extend, which is then instantiated with new. The constructor here takes an optional argument of type Object and can pass in properties such as EL, propsData, and so on.
import ToastConfig from './Toast.vue'
/ / the constructor
const ToastConstructor = Vue.extend(ToastConfig)
// Create the component with new
const instance = new ToastConstructor()Copy the code
When the Toast component is created, two prop: visible, MSG must be passed. When new is instantiated, the propsData parameter is configured to set the prop required by the component.
const instance = new ToastConstructor({
propsData: {
msg: 'msg'.visible: false}})Copy the code
Component creation and mounting are two different concepts. When a component is created, the mount phase has not started and the node is not included in the DOM element. It will not be rendered by the browser until it is mounted. When creating the instance, you set not only the propsData property, but also the mount point EL property, and attach the component to document.body.
const instance = new ToastConstructor({
el: document.createElement('div'),
propsData: {.msg: 'msg'.visible: false}})// Mount the component after it is successfully created
document.body.appendChild(instance.$el)Copy the code
Once mounted, the TOAST component is displayed. Turn on another timer and hide components after 3s.
Vue.nextTick((a)= > {
instance.visible = true
setTimeout((a)= > {
instance.close()
}, 3000)})Copy the code
Component destruction
Trigger the transitionEnd event when the Toast component’s hidden animation ends. Instance. $el returns the root element of the component, listens for the transitionEnd event, destroys the component in the callback, and removes it from the DOM tree.
// Add two functions to ToastConstructor that destroy components and remove DOM elements
// Hide components
ToastConstructor.prototype.close = function () {
this.visible = false
this.$el.addEventListener('transitionend'.this.destroyeInstance.bind(this))}// Destroy the component and remove the DOM element
ToastConstructor.prototype.destroyeInstance = function () {
this.$destroy(true)
this.$el.removeEventListener('transitionend'.this.destroyeInstance)
this.$el.parentNode.removeChild(this.$el)
}Copy the code
Click here for the full code snippet.
3. Make small adjustments
If the toast function is called frequently for a short period of time, multiple Toast components exist under document.body, and the latter overwrites the former. Given the nature of mobile, we expect document.body to have only one TOAST component at any given point in time, no matter how frequently the TOAST function is called. The following adjustment ideas are roughly as follows:
- Check whether the Toast component exists
- If no, create one
- If so, reset visible and MSG in State, remove the destroy component timer, and remove listening for transitionEnd time
The code needs some tweaking.
// Define two variables outside the function
// Instance is also set to NULL when the component is destroyed
let instance = null
let timer = null
function toast (msg = 'Default information') {
// Check whether instance exists
if (instance) {
instance.visible = true
instance.msg = msg
if (timer) {
clearInterval(timer)
}
instance.$el.removeEventListener('transitionend', instance.destroyeInstance)
} else {
/ /...
}
// ...
}Copy the code
Click here for the full code snippet.
Of course, we can go one step further and register the toast function as a Vue plug-in and call it from this.$toast where necessary. The message of Element-UI and Toast of VUX support plug-in calls.
4. To summarize
Compared to some mature Vue UI libraries, such as mint-UI’s Toast component, the current Toast component has many shortcomings. However, by writing a very simple Toast component, we have learned some concepts of Vue components, learned how to manually create and destroy components, and made some simple animations with transition, which will help us better understand the ideas of Vue components. Moreover, when we use some components of third-party libraries in the future, You get a rough idea of how it works.
The resources
- Mint – UI Toast
- The Toast vux
- Cube – UI Toast