How to package a vue plugin

First create an index.js file in the toast folder, create an object in the js file, and export it

// index.js
const toast = {}
export default toast

Import this file in main.js and use it

// main.js
import toast from 'toast/index.js'
Vue.use(toast)

We know that use is to call the install method of the object, so we need to write the install method in index.js

// index.js 
const toast = {} 
toast.install = function() { 
    // console.log() Here you can make an output by yourself to see if it is called 
} 
export default toast

After doing the output, you should know that this method is indeed called. At this time, we can do some things in this install method:

Get the toast component

Add components to the page

Give the component's display method to the vue instance

Explain the idea here

You must first get the component before you can operate the component.

Secondly, find a way to add the component to the page, so that it does not need to be introduced in other components, and a line of code can display the small box on the page.

Next, we need to give the display method of the component to the prototype attribute of the vue instance, so that we can directly this.$toast.show()

To write the code for install

toast.install = function (Vue) { 
    console.log('used') 
    // 1. Create a component constructor 
    const toastConstructor = Vue.extend(Toast) 
    // 2. Use the component constructor to create a component 
     const toast = new toastConstructor() 
    // 3. Manually mount the component on an element 
    toast.$mount(document.createElement('div')) 
    // 4. Insert the node into the page, $el is the node 
    document of the component. body.appendChild(toast.$el) 
    // 5. Add the component to the vue instance 
    Vue.prototype.$toast = toast 
}

To explain the code here:

The install method will automatically pass in a parameter, which is an object of Vue

It is not feasible for us to directly insert toast into the page, because the component is a virtual dom, not a node node

So we need to create a real dom through the component, and then mount it into the page

The steps are, use extend to create a component constructor, use the component constructor to instantiate a component object, manually mount the component object to an element, and then insert it into the page

Finally, give this component instance to Vue.prototype.$toast and we can use this.$toast elsewhere

Guess you like

Origin blog.csdn.net/asfasfaf122/article/details/128787947