Personal understanding, a lot of advice
- usage
If the plug-in is an object, the install method must be provided. If the plug-in were a function, it would be used as the install method. When the install method is called, Vue is passed in as an argument.
-
Demo (Custom plug-in)
use.js
import Vue from 'vue'; // Introduce custom components import {sortStr,loadingTemp} from './index'; Vue.use(sortStr); Vue.use(loadingTemp); Copy the code
plugin.js
const sortStr = { install(Vue) { Vue.prototype.sortStr = (str = ' ') = > str.split(' ').sort().join(' '); }};function loadingTemp(Vue,arr = []) { let _temp = '
loading..' Vue.component('Loading', {template: _temp }) } export {sortStr,loadingTemp} Copy the codemain.js
Need to introduce JS
import './use.js' Copy the code
- Component directly used in
`<Loading></Loading>` this.sortStr('cba'); //console abc Copy the code
-
Source code (annotation)
Vue.use = function (plugin: Function | Object) {
// indexOf determines whether the plug-in already exists in the plug-in
const installedPlugins = (this._installedPlugins || (this._installedPlugins = []))
if (installedPlugins.indexOf(plugin) > -1) {
return this
}
// Process parameters to convert the original parameters into arrays
const args = toArray(arguments.1);
// Insert this (VUE) first
args.unshift(this)
if (typeof plugin.install === 'function') {
// The install function is defined
plugin.install.apply(plugin, args)
} else if (typeof plugin === 'function') {
// is itself a function
plugin.apply(null, args)
}
installedPlugins.push(plugin)
return this
}
Copy the code