全局指令在main.js中定义
全局自定义指令原本都是要写到main.js中的,但是如果全局自定义指令比较多的话,都直接写到main.js中,也不好, 这个时候,就需要以插件的格式定义全局指令
以插件的方式定义全局指令
import { useIntersectionObserver } from '@vueuse/core'
import defaultImage from '@/assets/images/200.png'
const myDirective = {
install (app) {
app.directive('imgLazy', {
// 省略其他生命周期钩子函数
// el: 使用了指令的dom
// binding.value: v-指令名="binding.value就是这里表达式的值"
mounted (el, binding) {
el.src = defaultImage
const { stop } = useIntersectionObserver(el,
([{ isIntersecting }], observeDom) => {
// 如果isIntersecting为true
if (isIntersecting) {
stop()
el.src = binding.value
el.onerror = function () {
el.src = defaultImage
}
}
}, { threshold: 0 })
}
})
}
}
export default myDirective
//然后在main.js中导入这个页面插件
import directives from '@/directives/index.js'
// import defineDirective from '@/directives'
const app = createApp(App)
app.use(store).use(router).use(components).use(directives).mount('#app')