全局注册

注册全局组件

import loading from '@/components/loading'
app.component('Loading', loading)

webpack 项目中可能需要把某个文件夹下的组件全都注册为全局组件,可以使用如下写法:

// main.js
const componentsContext = require.context('./components/global', true, /\.js$/)
componentsContext.keys().forEach(component => {
  const componentConfig = componentsContext(component)
  const ctrl = componentConfig.default || componentConfig // 兼容 export 和 module.export
  Vue.component(ctrl.name, ctrl)
})

注册全局插件

app.use(xxx)

如果插件是一个对象,必须包含一个install方法,如果插件是一个函数,将作为install()方法,install 在执行时,会将 vue 实例作为第一个参数传进去。

//第一个参数是插件的名字,后面的参数将在 install() 方法的vue参数后依次传入
app.use(Toast, router)

注册全局自定义指令

一般项目场景中注册全局自定义指令可以使用如下方案:

// 在src目录下建 directives 文件夹

// /src/directives/index.js
import DragDialog from './drag-dialog'

// main.js
import directives from './directives'

const install = app => {
  app.directive('drag-dialog', Drag)
}

export default install
app.use(directives)

vite 工程配置 router component 属性时动态加载 vue 文件

// path: vue 组件路径
const modules = import.meta.glob('../views/**/*.vue')
function loadView (vuePath: string) => {
  for (const path in modules) {
    const dir = path.split('views')[1].split('.vue')[0]
    if (dir === vuePath || dir === `${vuePath}/index`) {
      return () => modules[path]()
    }
  }
}