vue2,vue3引入全局组件的异同

2,544 阅读1分钟

vue2全局组件的定义

import ScreenFull from '@/components/FUllScreen'
// 使用插件
const MyPlugin = {
  install(Vue) {
    Vue.component(PageTool.name, PageTool)
    // console.log('插件注册,调用install,传入的参数是', Vue)
    // 在Vue的构造器的原型上添加这个功能
    // 添加全局过滤器,组件,
    Vue.component(ScreenFull.name, ScreenFull)
  }
}
export default MyPlugin

main.js中:

import MyPlugin from '@/plugin'
Vue.use(MyPlugin)

vue3全局组件的定义

import XtxCarousel from './xtx-carousel.vue'

const myPlugin = {
  install (app) {
    // app为vue的实例
    // app.component('组件名',组件对象)
    app.component(XtxCarousel.name, XtxCarousel)
  }
}

export default myPlugin

在main.js中:

// 引入全局组件
import myPlugin from '@/components/index'

createApp(App).use(store).use(router).use(myPlugin).mount('#app')

总结:

二者都是通过调用install方法来实现的,

vue2调用时传了vue构造器的一个参数,将组建挂载到vue的原型链上面,

vue3调用时使用的是:new了个vue的实例

使用方法相同 调用component方法,传两个参数,第一个参数为组件的名字,第二个为组件对象

在main.js中:

二者都是通过.use()将组件挂载到全局使用