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

JavaScript selector functions querySelector and querySelectorAll

Table of contents 1. querySelector queries a sing...

Windows 10 + mysql 8.0.11 zip installation tutorial detailed

Prepare: MySQL 8.0 Windows zip package download a...

CocosCreator classic entry project flappybird

Table of contents Development Environment Game en...

Summary of ten Linux command aliases that can improve efficiency

Preface Engineers working in the Linux environmen...

Common usage of hook in react

Table of contents 1. What is a hook? 2. Why does ...

Nginx uses ctx to realize data sharing and context modification functions

Environment: init_worker_by_lua, set_by_lua, rewr...

Use javascript to create dynamic QQ registration page

Table of contents 1. Introduction 1. Basic layout...

Advanced techniques for using CSS (used in actual combat)

1. The ul tag has a padding value by default in Mo...

htm beginner notes (must read for beginners)

1. What is HTML HTML (HyperText Markup Language):...

Implementation of CSS equal division of parent container (perfect thirds)

The width of the parent container is fixed. In or...

Beginners learn some HTML tags (1)

Beginners can learn HTML by understanding some HT...

Implementation of Vue package size optimization (from 1.72M to 94K)

1. Background I recently made a website, uidea, w...

Example of adding music video to HTML page

1. Video tag Supports automatic playback in Firef...

Detailed explanation of keepAlive use cases in Vue

In development, it is often necessary to cache th...