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 Vue routing router

Table of contents Using routing plugins in a modu...

Sample code for programmatically processing CSS styles

Benefits of a programmatic approach 1. Global con...

7 skills that great graphic designers need to master

1》Be good at web design 2》Know how to design web p...

Essential conditional query statements for MySQL database

Table of contents 1. Basic grammar 2. Filter by c...

40 CSS/JS style and functional technical processing

1- Styling dropdown select boxes - Modify the dro...

A brief analysis of the basic implementation of Vue detection data changes

Table of contents 1. Object change detection 2. Q...

Three Ways to Lock and Unlock User Accounts in Linux

If you already have some kind of password policy ...

React Diff Principle In-depth Analysis

Table of contents Diffing Algorithm Layer-by-laye...

Mysql inner join on usage examples (must read)

Grammatical rules SELECT column_name(s) FROM tabl...

Eight ways to implement communication in Vue

Table of contents 1. Component Communication 1. P...

js dynamically implements table addition and deletion operations

This article example shares the specific code for...

Vue integrates a rich text editor that supports image zooming and dragging

need: According to business requirements, it is n...

vue3+ts+EsLint+Prettier standard code implementation

Table of contents use Use of EsLint Add a profile...