(1) What is plug-in (check)

The official explanation

Plug-ins are usually used to add global functionality to a Vue. (This sentence will suffice)

There are no hard and fast limits to what a plug-in can do — there are usually:

  1. Add global methods or properties. Such as: the vue – custom – element
  2. Add global resources: directives/filters/transitions, etc. Such as the vue – touch
  3. Add some component options through global blending. Such as the vue – the router
  4. Add Vue instance methods by adding them to Vue. Prototype.
  5. A library that provides its own API and provides one or more of the functions mentioned above. Such as the vue – the router

— — — — — — — —

Like above, you can add a plug-in, but the Vue documentation is a bunch? Plugins in vue. js should expose an install method. The first argument to this method is the Vue constructor, and the second argument is an optional option object:

MyPlugin.install = function (Vue, options) {
  // 1. Add a global method or property
  Vue.myGlobalMethod = function () {
    / / logic...
  }

  // 2. Add global resources
  Vue.directive('my-directive', {
    bind (el, binding, vnode, oldVnode) {
      / / logic...}... })// 3. Inject component options
  Vue.mixin({
    created: function () {
      / / logic...}... })// 4. Add instance methods
  Vue.prototype.$myMethod = function (methodOptions) {
    / / logic...}}Copy the code

Why is install() officially used? This is because think about engineering problems (problems that actually happen in engineering projects)! If toast=function() {} if toast=function() {} if toast=function() {} This overrides the previous attributes and we need to import vue separately, import vue from ‘vue’. If the vUE here is different from the vue version the user is using, for example, the user is using vue2, We said import Vue from ‘Vue ‘, doesn’t that make a mistake

The above problems need to be solved by methods in VUE:

Let’s create a plug-in

Then use it as the VUE documentation says

Success!

Develop a Toast plugin

Modify code:

Click the button