文章目录
一 vue 2
1 全局注册组件
src下创建component/index.js文件
// 导入相关组件
import '注册组件名' from './...'
export default {
install (Vue) {
Vue.component('要使用时的名称', 注册组件名 )
}
}
main.js中导入注册
import Component from '@/component'
Vue.use (Component ) //注册自己的组件
组件使用
<template>
<div>
// 第一种方式
<要使用时的名称/>
// 第二种方式
<component :is='组件名' />
</div>
</template>
2 自定义指令
export default {
Vue.directive('指令名', {
// el 当前元素,bind.value 可访问传入的值
inserted (el, bind) {
el.xxx = bind.value
}
})
}
新建 src下新建tools/directive.js文件
export const LazyLoad = () => {
// el 当前元素,bind.value 可访问传入的值
Vue.inserted (el, bind) {
el.xxx = bind.value
}
}
main.js中注册使用
import Vue from 'vue'
import Directives from './utils/directives'
Vue.use(Directives)
二 vue3
1 全局注册组件和自定义指令
创建 components/library/index.js
export default {
install (app) {
// 自定义组件
app.component(XtxSkeleton.name, XtxSkeleton)
app.component(xtxCarousel.name, xtxCarousel)
app.component(xtxMore.name, xtxMore)
// 自定义指令
defineDirective(app)
}
}
const defineDirective = (app) => {
// directive('指令名称',fn)自定义指令
app.directive('lazy', {
// vue 2.0用inserted 监听DOM是否创建好
// vue3.0 用mounted
mounted (el, binding) { // el监听的元素,binding传入的值
const observer = new IntersectionObserver(([{ isIntersecting }]) => {
// 是否进入可视区
if (isIntersecting) {
// 停止观察
observer.unobserve(el)
// 图片加载失败
el.onerror = () => {
el.src = defaultImg
}
el.src = binding.value
}
}, {
// 进入可视区立即开始
threshold: 0
})
// 开启观察
observer.observe(el)
}
})
}
main.js 中注册
import ui from './components/library'
createApp(App).use(ui).mount('#app')