Write plug-ins
Vue projects can use many plug-ins to enrich their functionality, such as VUE-Router, Vuex… , so many plug-ins for us to use, save us a lot of manpower and material resources, that these plug-ins are developed? If we want to have a vUE plug-in of our own, here is how to write a vue plug-in of our own.
1.1 Object containing the install() method
A Vue plug-in can be an Object containing the Install method, which is called when the plug-in is called, as follows:
Install: (app, options) => {console.log('app', app); install: (app, options) => {console.log('app', app); console.log('options', options); // Do some processing //...... }}Copy the code
1.2 Through function
A Vue plug-in can also be a function function, in which case the plug-in will call the function function itself, as shown below:
export default function TestPlugin(app, options) {
console.log('app', app);
console.log('options', options);
}
Copy the code
Second, use plug-ins
You’ve already explained how to write your own plug-ins. Once you’ve written them, you need to use them. How do you use them? In fact, it is very simple to use, the application context instance provides the corresponding use method.
app.use(plugin, [options]); // Returns an application instance, so it can be chained to add new plug-insCopy the code
How does app.use() implement the plugin
Why can app.use() use these plug-ins? In the spirit of “know what it is and know why,” let’s find out why. Here is the corresponding source code:
Function createApp(rootComponent, rootProps = null) {//... const installedPlugins = new Set(); Const app = (context.app = {//... use(plugin, ... options) { if (installedPlugins.has(plugin)) { warn(`Plugin has already been applied to target app.`); } else if (plugin && shared.isFunction(plugin.install)) { installedPlugins.add(plugin); plugin.install(app, ... options); } else if (shared.isFunction(plugin)) { installedPlugins.add(plugin); plugin(app, ... options); } else { warn(`A plugin must either be a function or an object with an "install" ` + `function.`); } return app; } / /... }); return app; };Copy the code
The code above is simple to read and does a few things:
- Use the Set structure to store the plug-in, and throw an exception when the plug-in exists.
- Execute the corresponding plug-in by determining whether the install method exists or is a function.
- Pass the APP context instance and options as parameters when executing the plug-in;