vue3 directive

一见如故

app.directive('xxx', { // 多个生命周期,同组件的生命周期 mouted(el, binding){} })
  • 涉及到dom操作,第一时间想到封装成指令
  • 解构binding
    1、value // 指’sss’
    2、oldValue // 一般用于beforeUpdate和updated周期中
    3、arg // 传给指令的参数,‘abc’
    4、modifiers // 打印得{foo: true, bar: true}

setup语法糖中定义指令

// 定义v开头的驼峰式命名的变量,值为一个对象或者函数
const vFocus = {
  mounted: (el) => el.focus()
}

directive的第二个参数可以是一个函数

// 在mouted和updated生命周期中调用,其他生命周期不关注
app.directive('xxx', (el, binding) => {})

指令的值可以传一个对象

注意及时卸载钩子函数定义的全局变量、定时器、事件等

示例v-debounce

app.directive('debounce',(el, {value}) => {
	let timer
	el.addEventListener('click', () => {
		if(timer) {
			clearTimeout(timer)
		}
		timer = setTimeout(() => {
			value()
		}, 500)
	})
})

你可能感兴趣的:(VUE,架构能力,vue.js,javascript,前端)