自定义指令的用法及模块开发

79 阅读1分钟

相信大家应该对于Vue中自定义指令还是比较熟悉的,下面就简单的阐述一下自定义指令的基本使用以及在开发过程中一般如何使用

局部自定义指令以v-focus为例

//自定义指令局部注册
    
  directives: {
    focus: {
      inserted(el) {
        el.focus()
      }
    }
  }

在开发中我们可能会遇到的问题比如说,当图片有地址,但是地址没有加载成功时会触发图片的一个事件=>onerror 这个时候我们就需要自定义指令

 Vue.directive('imgerror',{
     // el 指令所在的元素
     // binding 指令的相关信息
     inserted(el,binding){
         el.onerror=function(){
             el.src = bindings.value
         }
     }
 })

然而为了避免main.js中的内容过多,我们通常会新建一个模块来统一管理所有的自定义指令:

新建 src/directives/index.js, 这个文件负责管理所有的自定义指令

export const imgerror ={
    inserted(el,binding){
        el.onerror=function(){
            el.src=binding.value
        }
    }
}
export const color = {
    inserted(el,bindings){
        el.style.color= binding.value
    }
}

这时我们只需要在main.js中引入就还可以. 方法一:按需导入 import {imgerror,color} from '@/directives' 注: 但是如果我们自定义过多的话还是比较麻烦的 方法二:按需导入时的重命名,使用as进行重命名

import {imgerror} from '@/directives'

import {imgerror as directives} from '@/directives'

//对于按需导入可以直接全部导入
import * as directives from '@/directives'

// 这里的directives是一个对象,会得到directives/index.js模块的所有的按需导出

以下就是在main.js对于指令的注册代码

import * directives from '@/directives'
// 然后遍历得到的对象,批量进行自定义指令的注册
方法一:
for (let key in directives){
 Vue.directive(key,directvies[key])
}
方法二:
Object.keys(directives).forEach(key=>Vue.directive(key,directives[key]))

以上为我们可能会遇到的问题!