核心是借助Vue内置的install方法结合循环方式注册到全局。
install方法的详细解释可以参考:vue中install方法_普通网友的博客-CSDN博客_vue install
1. 全局自定义指令注册
// directives文件下index.js文件中
const directives = {
'imageError': {
inserted(el, binding) {
el.src = el.src || binding.value
el.onerror = () => {
el.src = binding.value
}
}
},
'focus': {
inserted(el, binding) {
el.focus()
}
}
}
export default {
install(Vue) {
Object.keys(directives).forEach(key => {
Vue.directive(key, directives[key])
})
}
}
// ------------------------------------
// main.js中
import directives from '@/directives'
Vue.use(directives)
2. 全局自定义组件
// 在components文件夹下新建index.js文件,依次引入所有组件
import CustomMapMaker from './CustomMapMaker'
import UploadExcel from './UploadExcel'
import ImageUpload from './ImageUpload'
const components = {
CustomMapMaker,
UploadExcel,
ImageUpload
}
export default {
install(Vue) {
Object.keys(components).forEach(key => {
Vue.component(key, components[key])
})
}
}
// -------------------------------------------------
// 在main.js中全局注册
import components from '@/components'
Vue.use(components)
3. 全局过滤器
// 预定义多个过滤器
import * as filters from './filters'
export default {
install(Vue) {
Object.keys(filters).forEach(key => {
Vue.filter(key, filters[key])
})
}
}
// ----------------------------------------
// 在main.js中注册
import filters from '@/filters'
Vue.use(filters)
4. 全局混入
// 向外暴露混入
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters(['points'])
},
methods: {
checkPermission(point) {
return this.points.includes(point)
}
}
}
// --------------------------------------
// 在main.js中全局混入, 注意此处是Vue.mixin()
import mixin from '@/mixin'
Vue.mixin(mixin)