Vue.use()是Vue提供一个静态方法,用来向Vue注册插件。我们也可以以插件的形式来注册全局组件,方便统一管理及使用
插件:扩展vue原有的功能:全局组件,自定义指令,挂载原型方法,注意:没有全局过滤器。
vue2.0插件写法要素:导出一个对象,有install函数,默认传入了Vue构造函数,Vue基础之上扩展
vue3.0插件写法要素:导出一个对象,有install函数,默认传入了app应用实例,app基础之上扩展(主要区别就是install传入的不一样 main.js时使用方式不一样)
Vue2的做法
具体使用步骤
1.提供统一的入口文件
src/componets/index.js
引入,调用install()
2.在main.js中注册插件
之后再注册全局组件,直接在src/componets/index.js
中引入 注册即可
Vue3的做法
1.封装组件:src/components/library/xtx-skeleton.vue
2.封装插件:插件定义 src/componets/library/index.js
import XtxSkeleton from './xtx-skeleton.vue'
export default {
install (app) {
// 在app上进行扩展,app提供 component directive 函数
// 如果要挂载原型 app.config.globalProperties 方式
app.component(XtxSkeleton.name, XtxSkeleton)
}
}
3.在main.js中使用
+import XtxUI from './components/library'
+createApp(App).use(store).use(router).use(XtxUI).mount('#app')