在开发中我们有一些基础组件非常的常用,每一次用的话都import导入未免感觉麻烦。
在自定义指令的时候,我们通过app实现了全局的注册
注册一个图片懒加载自定义指令:
import { useIntersectionObserver } from '@vueuse/core'
// 定义懒加载插件
export const LazyPlugin = {
install(app) {
// 自定义全局指令
app.directive('img-lazy', {
mounted(el, binding) {
// el: 指令绑定的那个dom元素,这里也就是img
// binding: binding.value 指令等于后面绑定的表达式的值, 图片的url
const { stop } = useIntersectionObserver(el, ([{ isIntersecting }]) => {
if (isIntersecting) {
el.src = binding.value
stop()
}
})
}
})
}
}
我们可以通过install(app),来注册全局组件。
在要注册的文件下创建一个js文件作为注册的入口

在文件中注册组件
import ImageView from '@/components/imageView/index.vue'
import Sku from '@/components/XtxSku/index.vue'
export const componentPlugin = {
install(app) {
app.component('XtxImageView', ImageView)
app.component('XtxSku', Sku)
}
}
在main.js中注册
import { componentPlugin } from '@/components/index'
app.use(componentPlugin)
这样我们使用这些注册的全局组件时,就不用import导入了,直接使用即可。
903

被折叠的 条评论
为什么被折叠?



