vue3自定义指令

666 阅读2分钟

一、注册自定义指令

1.1、全局自定义指令

1.11 在vue2中,全局自定义指令通过 directive 挂载到 Vue 对象上,使用 Vue.directive('name',opt)

实例1:Vue2 全局自定义指令('focus')

Vue.directive('focus',{
 inserted:(el)=>{
  el.focus()
 }
})

inserted 是钩子函数,在绑定元素插入父节点时执行

1.12 在 vue3 中,vue 实例通过createApp 创建,所以全局自定义指令的挂载方式也改变了, directive 被挂载到 app上。

实例2:Vue3 全局自定义指令

main.js文件中全局自定义指令

//全局自定义指令
import App from './App.vue'
const app = createApp(App)
app.directive('focus',{
 mounted(el){
  el.focus()
 }
})

//组件使用
<input type="text" v-focus />

1.13 实例3:Vue3 全局自定义指令(模块化)

1.131 copy.js

const copy = {
    // 全局自定义复制指令 `v-copy`
    mounted(el, {value}) {
        el.$value = value;
        el.handler = () => {
            el.style.position = 'relative';
            if (!el.$value) {
                // 值为空的时候,给出提示
                alert('无复制内容');
                return
            }
            // 动态创建 textarea 标签
            const textarea = document.createElement('textarea');
            // 将该 textarea 设为 readonly 防止 iOS 下自动唤起键盘,同时将 textarea 移出可视区域
            textarea.readOnly = 'readonly';
            textarea.style.position = 'absolute';
            textarea.style.top = '0px';
            textarea.style.left = '-9999px';
            textarea.style.zIndex = '-9999';
            // 将要 copy 的值赋给 textarea 标签的 value 属性
            textarea.value = el.$value
            // 将 textarea 插入到 el 中
            el.appendChild(textarea);
            // 兼容IOS 没有 select() 方法
            if (textarea.createTextRange) {
                textarea.select(); // 选中值并复制
            } else {
                textarea.setSelectionRange(0, el.$value.length);
                textarea.focus();
            }
            const result = document.execCommand('Copy');
            if (result) alert('复制成功');
            el.removeChild(textarea);
        }
        el.addEventListener('click', el.handler); // 绑定点击事件
    },
    // 当传进来的值更新的时候触发
    updated(el, {value}) {
        el.$value = value;
    },
    // 指令与元素解绑的时候,移除事件绑定
    unmounted(el) {
        el.removeEventListener('click', el.handler);
    },
}
export default copy

1.132 lazyload.js

const lazyload = {
  mounted (el, binding) {
      const observer = new IntersectionObserver(([{ isIntersecting }]) => {
        if (isIntersecting) { // isIntersecting判断是否进入视图
          observer.unobserve(el) // 进入视图后,停止监听
          el.onerror = () => { // 加载失败显示默认图片
              el.src = '/img/a.jpg'
          }  
          el.src = binding.value // 进入视图后,把指令绑定的值赋值给src属性,显示图片
        }
      }, {
        threshold: 0.01 // 当图片img元素占比视图0.01时 el.src = binding.value
      })
      observer.observe(el) //观察指令绑定的dom
    }
  }
}
export default lazyload

1.133 directive.js

import copy from './modules/copy'
import lazyload from './modules/lazyload'
const directives =  {
  copy,
  lazyload,
}

export default directives

1.134 main.js文件中全局自定义指令

//全局自定义指令
import App from './App.vue'
//引入封装指令模块
import directives from '@/utils/directive.js'
const app = createApp(App)

Object.keys(directives).forEach(key => {  //Object.keys() 返回一个数组,值是所有可遍历属性的key名
    app.directive(key, directives[key])  //key是自定义指令名字;后面应该是自定义指令的值,值类型是string
})

//组件使用
<input type="text" v-focus />

1.2、局部自定义指令

在组件内部,使用 directives 引入的叫做局部自定义指令。Vue2 和 Vue3 的自定义指令引入是一模一样的。

实例3:局部自定义指令

<script>

//局部自定义指令
const defineDir = {
 focus:{
  mounted(el){
   el.focus()
  }
 }
}

export default {
 directives:defineDir,
 setup(){}
}

</script>

局部自定义指令setup用法

<script setup>

//局部自定义指令
const defineDir = {
 focus:{
  mounted(el){
   el.focus()
  }
 }
}

</script>

二、自定义指令中的生命周期钩子函数

2.1 一个指令定义对象可以提供如下几个钩子函数(都是可选的,根据需要引入)

  • created :绑定元素属性或事件监听器被应用之前调用。该指令需要附加需要在普通的 v-on 事件监听器前调用的事件监听器时,这很有用。
  • beforeMounted :当指令第一次绑定到元素并且在挂载父组件之前执行。
  • mounted :绑定元素的父组件被挂载之后调用。
  • beforeUpdate :在更新包含组件的 VNode 之前调用。
  • updated :在包含组件的 VNode 及其子组件的 VNode 更新后调用。
  • beforeUnmounted :在卸载绑定元素的父组件之前调用
  • unmounted :当指令与元素解除绑定且父组件已卸载时,只调用一次。

实例4:测试指令内生命周期函数执行

<template>
 <div>
  <input type="text" v-focus  v-if="show"><br>
  <button @click="changStatus">{{show?'隐藏':'显示'}}</button>
 </div>
</template>

//局部自定义指令
const autoFocus = {
 focus:{
  created(){
   console.log('created');
  },
  beforeMount(){
   console.log('beforeMount');
  },
  mounted(el){
   console.log('mounted');
  },
  beforeUpdated(){
   console.log('beforeUpdated')
  },
  updated(){
   console.log('updated');
  },
  beforeUnmount(){
   console.log('beforeUnmount');
  },
  unmounted(){
   console.log('unmounted');
  }
 },
}

import { ref } from 'vue'
export default {
 directives:autoFocus,
 
 setup(){
  const show = ref(true)
  return {
   show,
   changStatus(){
    show.value = !show.value
   }
  }
 }

}

通过点击按钮,创建 input 元素的时候,会触发 createdbeforeMount 和 mounted 三个钩子函数。

隐藏 input 元素的时候,会触发 beforeUnmount 和 unmounted 

然而我们添加的 beforeUpdate 和 updated 函数并没有执行。

此时我们把 input 元素上的 v-if 修改成 v-show 就会执行上述两个方法了,具体的执行情况自行验证下。

2.2 从 vue2 升级到 vue3 ,自定义指令的生命周期钩子函数发生了改变,具体变化如下:

  • bind 函数被替换成了beforeMounted
  • update 被移除。
  • componentUpdated 被替换成了updated
  • unbind 被替换成了 unmounted
  • inserted 被移除。

三、自定义指令钩子函数的参数

钩子函数被赋予了以下参数:

  • el:指令所绑定的元素,可以直接操作DOM
  • binding:是一个对象,包含该指令的所有信息。

binding 包含的属性具体的分别为:

  • arg 自定义指令的参数名。
  • value 自定义指令绑定的值。
  • oldValue 指令绑定的前一个值。
  • dir 被执行的钩子函数
  • modifiers:一个包含修饰符的对象。
<template>
 <div>
  <div v-fixed >定位</div>
 </div>
</template>

<script>
//自定义指令动态参数
const autoFocus = {
 fixed:{
  beforeMount(el,binding){
   console.log('el',el)
   console.log('binding',binding)
  }
 }
}

export default {
 directives:autoFocus,
 setup(){
 }
}
</script>

四、自定义指令参数

自定义指令的也可以带参数,参数可以是动态的,参数可以根据组件实例数据进行实时更新。

实例5:自定义指令动态参数

<template>
 <div>
  <div v-fixed:pos="poseData" style="width:100px;height:100px;background:grey">定位</div>
 </div>
</template>

<script>
//自定义指令动态参数
const autoFocus = {
 fixed:{
  beforeMount(el,binding){
   el.style.position = "fixed"
   el.style.left = binding.value.left+'px'
   el.style.top = binding.value.top + 'px'
  }
 }
}

export default {
 directives:autoFocus,
 
 setup(){
  const poseData = {
   left:20,
   top:200
  }
  return {
   poseData,
  }
 }

}

</script>

五、 封装指令实例

5.1 封装复制指令实例copy.js

const copy = {
    // 全局自定义复制指令 `v-copy`
    mounted(el, {value}) {
        el.$value = value;
        el.handler = () => {
            el.style.position = 'relative';
            if (!el.$value) {
                // 值为空的时候,给出提示
                alert('无复制内容');
                return
            }
            // 动态创建 textarea 标签
            const textarea = document.createElement('textarea');
            // 将该 textarea 设为 readonly 防止 iOS 下自动唤起键盘,同时将 textarea 移出可视区域
            textarea.readOnly = 'readonly';
            textarea.style.position = 'absolute';
            textarea.style.top = '0px';
            textarea.style.left = '-9999px';
            textarea.style.zIndex = '-9999';
            // 将要 copy 的值赋给 textarea 标签的 value 属性
            textarea.value = el.$value
            // 将 textarea 插入到 el 中
            el.appendChild(textarea);
            // 兼容IOS 没有 select() 方法
            if (textarea.createTextRange) {
                textarea.select(); // 选中值并复制
            } else {
                textarea.setSelectionRange(0, el.$value.length);
                textarea.focus();
            }
            const result = document.execCommand('Copy');
            if (result) alert('复制成功');
            el.removeChild(textarea);
        }
        el.addEventListener('click', el.handler); // 绑定点击事件
    },
    // 当传进来的值更新的时候触发
    updated(el, {value}) {
        el.$value = value;
    },
    // 指令与元素解绑的时候,移除事件绑定
    unmounted(el) {
        el.removeEventListener('click', el.handler);
    },
}
export default copy

5.1 封装图片懒加载指令实例lazyload.js

const lazyload = {
  mounted (el, binding) {
      const observer = new IntersectionObserver(([{ isIntersecting }]) => {
        if (isIntersecting) { // isIntersecting判断是否进入视图
          observer.unobserve(el) // 进入视图后,停止监听
          el.onerror = () => { // 加载失败显示默认图片
              el.src = '/img/a.jpg'
          }  
          el.src = binding.value // 进入视图后,把指令绑定的值赋值给src属性,显示图片
        }
      }, {
        threshold: 0.01 // 当图片img元素占比视图0.01时 el.src = binding.value
      })
      observer.observe(el) //观察指令绑定的dom
    }
  }
}
export default lazyload

六、自定义指令使用场景

  • 需要对普通 DOM 元素进行底层操作,这时候就会用到自定义指令。
  • 需要将某些功能在指定DOM元素上使用,但对于需要操作大量DOM元素或者大变动时候,推荐使用组件,而不是指令。