为了方便操作,我们都会封装一些全局指令为项目服务,这也会作为一个项目团队的基建。具体自定义指令请看这里
想要开发一个全局自定义指令,我们需要了解其生命周期钩子。
const myDirective = {
created(el, binding, vnode, prevVnode) {
},
beforeMount(el, binding, vnode, prevVnode) {},
mounted(el, binding, vnode, prevVnode) {},
beforeUpdate(el, binding, vnode, prevVnode) {},
updated(el, binding, vnode, prevVnode) {},
beforeUnmount(el, binding, vnode, prevVnode) {},
unmounted(el, binding, vnode, prevVnode) {}
}
<div v-example:foo.bar="baz">
binding
参数会是一个这样的对象:
{
arg: 'foo',
modifiers: { bar: true },
value: ,
oldValue:
}
注意,一般自定义指令不要使用在自定义组件上,如果该组件有多个根节点,那么vue将抛出一个警告。可能导致该指令不能达到预期效果。如果只有一个根节点那就无所谓了。
全局指令大体开发过程
我们一般在src
目录下创建一个directives
目录存放全局自定义指令。并提供一个index.js
作为全部指令的出口文件,在main.js中统一注册。
function customDirective(app) {
}
export function setCustomDirective(app) {
customDirective(app)
}
import { setCustomDirective } from './单独指令'
export default function setDirectives(app) {
setCustomDirective(app)
}
import { createApp } from 'vue'
import App from './App.vue';
import setDirectives from "./directives";
const app = createApp(App);
(function(app){
setDirectives(app)
app.mount('#app')
})(app)
auth 按钮级权限校验指令
这个功能对于后台管理系统是十分常见的,我记得当时我在实习的时候还搞不懂为啥需要按钮权限,因为当时在学校做项目的时候根本没有那么多权限控制。
对于不同的角色,他会具有不同的操作权限。为了方便控制这些操作权限,我们就可以开发一个指令去控制按钮级别的元素的显隐。
大致的实现过程
-
我们只需要使用
mounted
钩子即可。 -
获取当前用户的操作权限列表,一般放在全局store中。
-
支持指令的值是字符串或者数组,做适配处理。
-
如果在当前用户的操作列表中未查到指定的权限,我们将直接移除当前元素。
el.parentNode?.removeChild(el)
function authDirective(app) {
app.directive('auth', {
mounted(el, bindings) {
const permissions = ['a', 'b', 'c']
const authArr = Array.isArray(bindings.value)
? bindings.value
: [bindings.value]
let isExist = false
for (let item of authArr) {
if (permissions.includes(item)) {
isExist = true
break
} else {
continue
}
}
if (!isExist) el.parentNode?.removeChild(el)
}
})
}
export function setAuthDirective(app) {
authDirective(app)
}
format-time 格式化时间
一般后端给我们返回的时间都是时间戳,或者返回的是完整时间,我们需要对齐格式化成我们想要的,就需要用到一些时间格式化库,例如dayjs。为了方便操作,不需要在setup中写太多逻辑,我们就可以直接封装成一个自定义指令。
大致步骤如下
-
在
created
钩子中设置默认的格式。 -
mounted
中处理逻辑,一般后台返回的都是字符串时间戳,我们需要转为数字才可以传入dayjs做格式化。
import dayjs from 'dayjs'
function formatTimeDirective(app) {
app.directive('format-time', {
created(el, bindings) {
bindings.formatString = 'YYYY-MM-DD'
if (bindings.value) {
bindings.formatString = bindings.value
}
},
mounted(el, bindings) {
let time = el.textContent
if (!Object.is(Number(time), NaN)) {
time = Number(time)
}
el.textContent = dayjs(time).format(bindings.value)
}
})
}
export function setFormatTimeDirective(app) {
formatTimeDirective(app)
}
lazy 图片懒加载
我们对于懒加载指令做了一下处理
-
对图片做占位操作。
-
对图片做未成功加载占位操作。
-
只有当前元素可见时,才会去加载。
如果想了解更多图片懒加载关注马上更新
大致的实现过程
-
IntersectionObserver
api去判断当前元素是否可见。 -
new Image()
的onload,onerror去判断指定的图片资源是否加载完毕或者成功。做统一的异步处理。
el.setAttribute( 'src', 'https://lf3-cdn-tos.bytescm.com/obj/static/xitu_juejin_web/e08da34488b114bd4c665ba2fa520a31.svg' )
el.setAttribute('src', bindings.value)
el.setAttribute(
'src',
'https://p26-passport.byteacctimg.com/img/user-avatar/cba9b94c077e932fb1ef7f9d5abd447b~50x50.awebp'
)
function isExistContainer(el, bindings) {
const observer = new IntersectionObserver(async (entires) => {
if (entires[0].isIntersecting) {
const isLoaded = await isImgLoaded(el, bindings)
if (isLoaded) {
el.setAttribute('src', bindings.value)
} else {
el.setAttribute(
'src',
'https://p26-passport.byteacctimg.com/img/user-avatar/cba9b94c077e932fb1ef7f9d5abd447b~50x50.awebp'
)
}
observer.unobserve(el)
}
})
observer.observe(el)
return observer
}
async function isImgLoaded(el, bindings) {
return new Promise((resolve) => {
el.setAttribute(
'src',
'https://lf3-cdn-tos.bytescm.com/obj/static/xitu_juejin_web/e08da34488b114bd4c665ba2fa520a31.svg'
)
const img = new Image()
img.src = bindings.value
img.onload = () => {
resolve(true)
}
img.onerror = () => {
resolve(false)
}
})
}
function LazyDirective(app) {
app.directive('lazy', {
mounted(el, bindings) {
const observer = isExistContainer(el, bindings)
bindings.observer = observer
},
unmounted(el, bindings) {
bindings.observer.unobserve(el)
}
})
}
export function setLazyDirective(app) {
LazyDirective(app)
}
通过这三个例子可以看出,我们开发简单的自定义指令来说都是使用mounted
钩子即可。对于复杂一点的,我们还需要监听指令值的变化,需要用到updated
钩子。