🏆认识Vue.use()

🎉认识Vue.use()

关于 vue.use,官网的解释是这样的。

Vue.use( plugin )

  • 参数:

    • {Object | Function} plugin
  • 用法:

    安装 Vue.js 插件。如果插件是一个对象,必须提供 install 方法。如果插件是一个函数,它会被作为 install 方法。install 方法调用时,会将 Vue 作为参数传入。

    该方法需要在调用 new Vue() 之前被调用。

    当 install 方法被同一个插件多次调用,插件将只会被安装一次。

通过全局方法 Vue.use()使用插件

它在使用时实际是调用了该插件的install方法,所以引入的当前插件如果含有install方法我们就需要使用Vue.use(),例如在Vue中引用Element如下

import Vue from 'vue'          
import ElementUI from 'element-ui'; 
Vue.use(ElementUI);

因为在Element源码中会暴露除install方法,所以才需要用Vue.use()引入。

我们也可以在自己的vue项目中自己定义一个install方法,然后通过Vue.use()方法来引入测试一下

//plugin.js
const plugin = {
  install() {
    alert("我是install内的代码")
  },
}
export default plugin

//main.js
Vue.use(plugin) //我是install内的代码
posted @ 2021-12-16 19:56  花笺  阅读(50)  评论(0编辑  收藏  举报