In the process of project development, we may be used to use a variety of ready-made UI libraries, which can help us quickly complete the project development. For example, Toast and Message components that we often use in projects can be used only through JS invocation. Instead of using components in the usual way (import, components register), we will implement a component that is used through THE JS method. The final component we will implement is the Element-UI Message prompt

First, preparation

We first created a new folder in the project to store the component. I created it in/SRC /components/Message/, which is obviously where I put the prompts.

Vue and index.js files are created under Message. Js is the inbound and outbound of our component and the body from which the exported method is called.

Write component templates

We write a basic style first, then render it with JS calls, after which we refine the details of the component

  • index.vuecontent
<template>
  <div class="message"</p> </div> </template> <script>export default {
  name: 'Message'
}
</script>

<style scoped lang="stylus">
.message
  position fixed
  top 3vh
  left 50vw
  transform translateX(-50%)
  border 1px solid #EBEEF5
  background-color #edf2fc
  min-width 340px
  min-height 50px
  display flex
  align-items center
  box-sizing border-box
  padding 0 15px
  border-radius 5px
</style>
Copy the code
  • index.jscontent
import Vue from 'vue';
import Message from './index.vue';

const MessageConstructor = Vue.extend(Message);

export const $message = (a)= > {
  const instance = new MessageConstructor().$mount();
  document.body.appendChild(instance.$el);
}
Copy the code
  • Introduced in the page$messageMethods using
<script> import { $message } from '@/components/Message/index'; Export default {name: 'home', mounted() {// Return $message(); // Return $message(); } } </script>Copy the code
  • The effect

  • Break down

In index.vue is the code that we write the component, and we write the vue component in the same way that we normally do. The key code that allows us to use components by calling JS methods is in index.js.

There are only 7 lines of code in index.js, and at a glance you can easily guess that the core apis extend, $mount, and appendChild do exactly what they do

  1. Extend is a global API for Vue that accepts an object containing component options, such as this (official example)
Vue.extend({
  template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>'.data: function () {
    return {
      firstName: 'Walter'.lastName: 'White'.alias: 'Heisenberg'}}})Copy the code

Extend then creates a Vue ‘subclass’ (a Vue component that is not instantiated)

  1. $mount: If we are rightextendWhen the subclass is instantiated without the el option, the component is unmounted and needs to be called$mountMethod, manually mount it,$mountMethod that takes no arguments is automatically associated when mountedThis componentIf an argument is passed (can accept elements, element selectors), the element is associated with the element passed. Because of that we don’t have to call it$mountMethod, passing in the EL option at instantiation time;
import Vue from 'vue';
import Message from './index.vue';

const MessageConstructor = Vue.extend(Message);

export const $message = (a)= > {
  const instance = new MessageConstructor({
    el: document.createElement('div')});document.body.appendChild(instance.$el);
}
Copy the code
  1. AppendChild: At this point it is easy to understand and render the component into the body body
  2. Called when used last$messageMethod, nothing to say.

The key stuff is here. The Element UI component can pass in custom message contents and different types to display success or warning messages. Further, what if we need to do something else while the message is closed?

Three, perfect components

1. Customize component content

  • Modify theindex.jscode
import Vue from 'vue';
import Message from './index.vue';

const MessageConstructor = Vue.extend(Message);

// The method takes an options argument. Options must be of type object
export const $message = (options) = > {
  const instance = new MessageConstructor({
    el: document.createElement('div'),
    // Data is dynamically passed to the component when the component instance is generated
    data: options
  });
  document.body.appendChild(instance.$el);
}
Copy the code
  • Modify theindex.vuecode
<template>
  <div class="message"> / / content is changed to variable < p > {{message}} < / p > < / div > < / template > < script >export default {
  name: 'Message'// Data is newdata() {
    return {
      message: ' ',
    }
  }
}
</script>

<style scoped lang="stylus">
.message
  position fixed
  top 3vh
  left 50vw
  transform translateX(-50%)
  border 1px solid #EBEEF5
  background-color #edf2fc
  min-width 340px
  min-height 50px
  display flex
  align-items center
  box-sizing border-box
  padding 0 15px
  border-radius 5px
</style>
Copy the code
  • Content is passed in when called
$message({message: 'Sorry, registration failed'});
Copy the code

2. Add a prompt close button, which can be sensed by the caller after the prompt is closed

  • Modify theindex.vuecode
<template>
  <div class="message">
    <p>{{message}}</p>
    <i class="close" @click="handleClose"> &times; </i> </div> </template> <script>export default {
  name: 'Message'.data() {
    return {
      message: ' ',
    }
  },
  methods: {
    emitClose() {},
    handleClose() {
      this.$el.parentNode.removeChild(this.$el);
      this.emitClose();
    }
  }
}
</script>

<style scoped lang="stylus">
.message
  position fixed
  top 3vh
  left 50vw
  transform translateX(-50%)
  border 1px solid #EBEEF5
  background-color #edf2fcmin-width 340px max-width 500px min-height 50px display flex align-items center justify-content space-between box-sizing  border-box padding 0 15px border-radius 5px .close font-size 25px align-self flex-start margin-top -5px margin-right -9px cursor pointer </style>Copy the code
  • Modify theindex.jscode
import Vue from 'vue';
import Message from './index.vue';

const MessageConstructor = Vue.extend(Message);

export const $message = (options,methods = {}) = > {
  const instance = new MessageConstructor({
    el: document.createElement('div'),
    data: options,
    methods
  });
  document.body.appendChild(instance.$el);
}
Copy the code
  • call
$message({message: 'Sorry, registration failed, sorry'}, {
  emitClose() {
    console.log('Component closed'); }});Copy the code

TIP: If you want the caller to be aware when closing, in addition to methods, you can also pass data directly, but it is just a function, similar to

$message({
    message: 'Sorry, registration failed, sorry'.onClose() {
        console.log('Component closed'); }});Copy the code

Four, supplement

So far in fact we talk about the purpose of this component has been completed, is to tell you how to use the JS “message prompt” this kind of component, the rest of the success, failure, warning, timing off and other functions, not one implementation, time free you can achieve it.

If this article is useful to you, please give it a thumbs up. If you have any other questions or errors, please point them out in the comments. Bye bye!