Location>code7788 >text

Five minutes and a hundred lines of code, handwriting a vue project global common toast prompt component

Popularity:965 ℃/2024-10-18 09:29:25

Preface:

We've already shared how to quickly implement the global popup box component you need;

In the development of Vue projects, especially H5 page projects, there is another component that we use very often, it is not so big compared to the pop-up box, and does not need to be closed manually in the need to be more concise to prompt the user some information is very commonly used, it is thetoast Cue Component;

Next we'll walk you through handwriting a globaltoast Hint component that can be called directly when you need to use it anywhere in your project.

Check out past articles:

Fifteen minutes and two hundred lines of code, handwrite a vue project global common popup box

Step 1: New folder and main files

In a Vue project, generally speaking, our public components are placed in thesrc/componentsSo let's go directly to thesrc/components/toastCreate the following two new files under

  1. : The file istoast The content of the component is the same as if we were writing a normal vue component, containing thetoast structure, style, and underlying logic;
  2. : Registration component is a global component. Because the component is one we don't need to close manually and involves adding elements and automatically deleting elements, the file will have some element-level operations and logic, as opposed to the last installment of the popup box component's We'll go through it line by line below, and of course provide the full code, so scroll down.

Step 2: Write the component content

The component contents are as follows:

  1. Structure + js code
<template>
  <transition name="appear">
    <section class="toast" v-if="show">
      <div v-html="msg" class="toast-con"></div>
    </section>
  </transition>
</template>

<script type="text/ecmascript-6">
export default {
  name: "toast",
  data() {
    return {
      show: false,
      msg: '',
      time: 1000
    }
  },
  methods: {
    async open() {
      if () {
        return;
      }
       = true;
      let result = await ();
      return result;
    },
    close() {
      return new Promise((resolve) => {
        setTimeout(() => {
           = false;
          resolve(true);
        }, );
      });
    }
  }
}
</script>

Code Description:

  • We're using theVue (used form a nominal expression)transition component that wraps elements that need to be animated. name="appear" specifies the use of a transition effect called "appear";
    • See the Vue website for details:/guide/built-ins/
  • <div v-html="msg" class="toast-con"></div> This code is the main part of our toast, by way of thev-html + msg to dynamically insert attributes, the msg is modified in; the
  • methods: define the methods of the component.
    • open(): asynchronous method, use to show Toast, if it is already shown, it will return directly, otherwise set show to true and call close() method to wait for its completion.
    • close(): Returns a Promise that resolves after time milliseconds and sets show to false, thus hiding the Toast.
  1. type
<style lang="less" scoped>
.default-message {
  position: fixed;
  right: 0;
  top: 0;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1000;
  background: rgba(0, 0, 0, 0.7);

  .default-message-title {
    color: #333;
    margin: 0;
    line-height: 1.5;
    font-size: 18px;
    min-height: 18px;
    padding-top: 20px;
    text-overflow: ellipsis;
    font-weight: bold;
    cursor: move;
    text-align: center;
  }

  .default-message-content {
    width: 85%;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate3d(-50%, -50%, 0);
    background-color: #fff;
    border-radius: 6px;
    transition: all 0.2s ease-in;
    color: #999;
    font-size: 18px;
  }

  .default-message-value {
    padding: 28px 18px;
    text-align: center;
    position: relative;
    color: #999;
    text-align: center;
    font-size: 14px;
    color: rgba(102, 102, 102, 1);
  }
  .default-message-btns {
    // border-top: 1px solid #ddd;
    display: flex;
    height: 60px;
    position: relative;
    &:after {
      position: absolute;
      content: "";
      display: inline-block;
      left: 0;
      right: 0;
      top: 0;
      height: 1px;
      transform: scaleY(0.5);
      background: #ddd;
    }
    .default-message-btn {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 16px;
      padding: 0 3px;
    }
    .default-message-submit {
      color: #26a2ff;
    }
    .default-message-cancle {
      color: #999;
      position: relative;
      &:after {
        position: absolute;
        content: "";
        display: inline-block;
        top: 0;
        right: 0;
        bottom: 0;
        width: 1px;
        transform: scaleX(0.5);
        background: #ddd;
      }
    }
  }
  @keyframes fadeIn {
    from {
      opacity: 0;
    }
    to {
      opacity: 1;
    }
  }
}
</style>

Step 3: Register as a global component

import { createApp } from 'vue';
import ToastComponents from './';

const LayerToastId = 'layer-Toast-wrapper';

let Toast = async function (msg, time) {
  time = time || 2000;

  let ToastEl = (LayerToastId);
  // in the event thatDOMcontains this element non-implementation
  if (ToastEl) {
    return;
  }
  const div = ('div');
  ('id', LayerToastId)
  (div);
  let layerToastEl = createApp(ToastComponents).mount('#' + LayerToastId);
  // Modify the component'sdatavalue of
   = msg;
   = time;
  // Execute the methods in the component Waiting to close and returnpromise
  let hasClosed = await ();
  // (coll.) fail (a student)ToastDelete the outer element after the prompt is closed The timing is best aligned with thecssAnimation Consistency
  if (hasClosed) {
    setTimeout(() => {
      (div);
    }, 400);
  }
};
export default {
  install (app) {
    // pass (a bill or inspection etc)this.$toastinterviews
    .$toast = Toast;
  }
}

By this point, our popup box component is complete. Below we explain some of the more important code:

  • let Toast = async function This represents a Toast message, which we register as an asynchronous function because internally we need to use a timer to control the removal of the message container at regular intervals;

  • let layerToastEl = createApp(ToastComponents).mount('#' + LayerToastId);

    • What this code means is this: take the file is created as an application instance of Vue and mounted on the newly created div.
  • following A line-by-line explanation of the document:

// Introduce Vue's createApp function, which is used to create a Vue app instance.
import { createApp } from 'vue'; // Introduce Vue's createApp function for creating Vue app instances.
// Introduce the Toast component
import ToastComponents from '. /'; // Import Toast components import ToastComponents from '.

// Define a constant that stores the ID of the container element of the Toast component
const LayerToastId = 'layer-Toast-wrapper'; // Define a constant to store the ID of the container element of the Toast component.

// Define an asynchronous function, Toast, to display the Toast message.
let Toast = async function (msg, time) {
  // Defaults to 2000 milliseconds if no display time is specified.
  time = time || 2000;

  // Get whether a Toast container element already exists on the page.
  let ToastEl = (LayerToastId); // If it already exists, don't execute it.
  // If it already exists, return it without further code
  if (ToastEl) {
    if (ToastEl) { return; }
  }
  // Create a div element to be used as a container for the Toast component.
  const div = ('div'); // Set an ID for the div.
  // Set an ID for the div
  ('id', LayerToastId)
  // Add the created div to the body
  (div); // Add the created div to the body.

  // Create a Vue app instance and mount it on the newly created div.
  let layerToastEl = createApp(ToastComponents).mount('#' + LayerToastId); // Set the Toast component's message content.
  // Set the message content and display time for the Toast component
   = msg; }; // Set the content of the message and the time to be displayed for the Toast component.
   = time.

  // Call the open method of the Toast component to display the Toast and wait for it to close.
  let hasClosed = await (); // Call the open method of the Toast component to display the Toast and wait for it to close.
  // When the Toast closes, remove the Toast container element after a 400 millisecond delay.
  // The 400 millisecond delay can be matched to the timing of the CSS animation to ensure that the animation completes.
  if (hasClosed) {
    setTimeout(() => {
      (div); }, 400); { setTimeout(() => {
    }, 400);
  }
}.

// Export an object containing the install method to install the Toast feature in your Vue app.
export default {
  install (app) {
    // Add the Toast function to the global properties of the Vue app so that it can be accessed in any component via this.$toast
    . $toast = Toast; .
  }
}

Using popup boxes in projects

It's very easy and convenient to use, and there are several main uses:

  1. Used in Vue2:
// Simple use in Vue2
this.$toast("Simple use of Toast hints in Vue2 project"));

// There needs to be further action after the hint in Vue2: it can be any logic you want, including posting interfaces, page processing, etc.
await this.$toast("Toast prompt has further logic after use in Vue2 project", 3000); // This is the first time we've used this in a Vue2 project.
handleFunction(); // The function here represents the logic code that follows the tip
  1. Used in Vue3:
// To use it in Vue3, you need to import the app first.
import { app } from "@/main";

// Simple use in Vue3
. $toast("Simple use of Toast hints in Vue3 project", 3000);

// There needs to be further action after the hint in Vue2: it can be any logic you want, including posting interfaces, page processing, etc.
. $toast("Toast hint has further logic after use in Vue3 project"); .
handleFunction(); // The function here represents the logic code that follows the tip

Description:

  • We can pass in the appropriate display dwell time when using it, if it is passed in, it will be displayed at the default of 2000 milliseconds;
  • In Vue3, you can also put the$toast Re-save it so that you don't have to write a long one every time in the future....
import { app } from "@/main";

const toast = .$toast

toast("Easy to usetoastdraw attention to sth.");

Example of a toast image

Explanation: It will be closed automatically after 2000 milliseconds (or the dwell time we set).

Write it on the back.

This is a more basic and generic black semi-transparent prompt message, this side of the sample code is more complete, the details of the small requirements can be copied directly to the homework;

Background color, font, layout and other such details, because each business scenario is different, you can adjust it appropriately according to your needs;

By modifying the structure and styling code, you can make the styling of messages richer or more in line with your business needs;

Message components we are the same as the use of fixed units, if the partners of the project need to use responsive size, directly corresponding to replace the size of the unit (rem, vw) can be;

If it is helpful to you, give the author some attention, your support is the power of my constant updating!