Complete example of Vue encapsulating the global toast component

Complete example of Vue encapsulating the global toast component

Preface

I have recently experienced Vue. Toast is a commonly used component in the front end. This article introduces in detail the process of Vue encapsulating the global toast component. Let's take a look at the detailed introduction.

1. With vue-cli

1. Define the Toast component

// components/Toast

<template>
  <transition name="fade">
    <div v-show="visible">{{message}}</div>
  </transition>
</template>

<script>
export default {
  data () {
    return {
      visible: false,
      message: ''
    }
  }
}
</script>

<style scoped>
div {
  position: fixed;
  top: 30%;
  left: 50%;
  padding: 5px 20px;
  color: #fff;
  background-color: #424242;
  border-radius: 5px;
  text-align: center;
  transform: translate(-50%, -50%);
}
/* Vue animation transition effect settings */
.fade-enter-active,
.fade-leave-active {
  transition: opacity .5s;
}
.fade-enter, .fade-leave-to {
  opacity: 0;
}
</style>

2. Configure in main.js

import Vue from 'vue'
import App from './App.vue'
import Toast from './components/Toast'

// Define plugin object const ToastObj = {
  install: function (Vue) {
    // Create a Vue "subclass" component const ToastConstructor = Vue.extend(Toast)
    // Create an instance of this subclass and attach it to an element const instance = new ToastConstructor()
    console.log(instance)
    // Mount this instance to the dynamically created element and add the element to the global structure instance.$mount(document.createElement('div'))
    document.body.appendChild(instance.$el)

    // Register method on Vue's prototype chain to control component Vue.prototype.$toast = (msg, duration = 1500) => {
      instance.message = msg
      instance.visible = true
      setTimeout(() => {
        instance.visible = false
      }, duration)
    }
  }
}
Vue.use(ToastObj)

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
}).$mount('#app')

3. Use in other components

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data: () => {
    return {
      msg: 'HelloWord'
    }
  },
  mounted () {
  	//Use toast component this.$toast('Component mounted successfully')
  }
}
</script>

2. Without vue-cli

With the help of vue-cli, it is easy to import and export components, but without the help of build tools, other methods are needed.

1. Register the toast component

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="./static/vue/vue.min.js"></script>
</head>
<body>
  <div id="app">
    <my-button></my-button>
  </div>
  <div id="toast"></div>
  <script>
    // Define toast global component const Toast = Vue.component('toast', {
      data() {
        return {
          isShow: false,
          message: 'Global prompt',
          wrapperStyle: {
            position: 'fixed',
            top: '20%',
            left: '50%',
            zIndex: 10000,
            padding: '6px 12px',
            backgroundColor: '#424242',
            borderRadius: '5px',
            transform: 'translate(-50%, -50%)'
          },
          textStyle: {
            color: '#fff',
            fontSize: '14px'
          }
        }
      },
      template: `<div v-show="isShow" :style="wrapperStyle">
                  <span :style="textStyle">{{ message }}</span>
                </div>`
    })

2. Register the toast plugin

// Define plugin object const ToastObj = {
  install: function (Vue) {
    // Create a toast component instance and attach it to an element const instance = new Toast()
    //Mount this instance into the DOM instance.$mount('#toast')

    // Register method on Vue's prototype chain to control component Vue.prototype.$toast = ({message, duration = 2000} = {}) => {
      instance.message = message
      instance.isShow = true

      setTimeout(() => {
        instance.isShow = false
      }, duration)
    }
  }
}
//Register toast plugin Vue.use(ToastObj)

3. Use in other components

    Vue.component('my-button', {
      data() {
        return {
          wrapperStyle: {
            width: '70px',
            padding: '20px',
            backgroundColor: 'green'
          },
          textStyle: {
            color: '#fff',
            fontSize: '16px'
          }
        }
      },
      methods: {
        handleClick() {
          this.$toast({
            message: 'I clicked'
          })
        }
      },
      template: `<div :style="wrapperStyle" @click="handleClick">
                  <span :style="textStyle">Click prompt</span>
                </div>`
    })

    const vm = new Vue({
      el: '#app'
    })
  </script>
</body>
</html>

Summarize

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

You may also be interested in:
  • Vue encapsulated components are globally registered and referenced

<<:  Detailed explanation of Alibaba Cloud security rule configuration

>>:  Python connects to the database MySQL decompressed version installation configuration and encountered problems

Recommend

Detailed explanation of how to use the Vue date time picker component

This article example shares the specific code of ...

SystemC environment configuration method under Linux system

The following is the configuration method under c...

Docker container operation instructions summary and detailed explanation

1. Create and run a container docker run -it --rm...

Detailed explanation of using grep command in Linux

Linux grep command The Linux grep command is used...

How to design a web page? How to create a web page?

When it comes to understanding web design, many p...

Mysql transaction isolation level principle example analysis

introduction You must have encountered this in an...

XHTML Getting Started Tutorial: Commonly Used XHTML Tags

<br />Just like an article, our web pages sh...

30 minutes to give you a comprehensive understanding of React Hooks

Table of contents Overview 1. useState 1.1 Three ...

Summary of tips for setting the maximum number of connections in MySQL

Method 1: Command line modification We only need ...

CentOS7 installation GUI interface and remote connection implementation

Use the browser (webdriver)-based selenium techno...

Ubuntu 16.04 installation tutorial under VMware 12

This article shares with you the installation tut...

MySQL batch removes spaces in a certain field

Is there any way to remove spaces from a certain ...

MySQL configuration master-slave server (one master and multiple slaves)

Table of contents Ideas Host Configuration Modify...