面试常考题 - Vue.use

238 阅读1分钟

实例

main.js

import Vue from 'vue';
import App from './App';
import customComponent from './componets/index';
Vue.use(customComponent);
new Vue({
    render: h => h(App)
}).#mount('#app')

componets/index.js

import AComponent from. './componets/a-componet'
import BComponent from. './componets/b-componet'

const components = [
    AComponent,
    BComponent
];
const customComponent = {
    install(Vue) {
        // Vue构造函数提供给了我们,我们可以在这里对Vue本身做很多操作
        // 1. 注册全局组件--> Vue.component
        components.forEach(component => {
            Vue.component(component.name, component)
        });
        // 2. 自定义全局指令 --> Vue.directive
        
        // 3. 在Vue.prototype新增属性或方法 --> this.$message
        
        // 4. 定义全局过滤器 --> 被methods取代了
    }
}
export default customComponent;

Vue.use(plugin)

  • 参数 Object | Function
  • 用法 安装vue.js插件,如果插件是一个对象,必须提供install方法。
    如果插件是一个函数,它会被作为install方法,install方法调用时,会将VUe作为参数传入
    改方法需要在new Vue()之前被调用

Vue.use源码

import { toArray } from '../util/index';
export funciton initUse(Vue: GlobalAPI) {
    Vue.use = function(plugin: Function | Object) {
        const installedPlugins = (this._installedPlugins || (this._installPlugins = []));
        if (installedPlugins,indexof(plugin) > -1) {
            return this;
        }
        const agrs = toArray(arguments, 1);
        args.unshift(this);
        if (typeof plugin,install === 'function') {
            plugin.install.apply(plugin, args);
        } else if (typeof plugin === 'function') {
            plugin.apply(null, args);
        }
        installedPlugins.push(plugin);
        return this;
    }
}