vue2 对全局自定义指令一次性进行注册的方法

Rhea ·
更新时间:2024-09-20
· 915 次阅读

在src下新建文件夹directive/index.js

index.js文件中用来写入注册方法

/* * @Author: 周云芳 * @Date: 2022-06-28 15:21:41 * @LastEditors: 周云芳 * @LastEditTime: 2022-06-28 16:44:16 * @Description: 用于自动注册全局自定义指令 * 使用规则: * 根据导出的name在页面使用如directives对象中的name为el-drag-dialog,页面使用:v-el-drag-dialog */ const requireDirective = require.context('./', true, /\.js$/) // 自定义指令 let directives = {} requireDirective.keys().map((file) => { // console.log('file', file) const name = removerLastIndex(file) if (name) { directives = { ...directives, [name]: requireDirective(file).default } } return false }) function removerLastIndex (str) { const start = str.substring(2, str.length) // 去除路径中的./ start=el-drag-dialog/index.js // str = login/index // 获取最后一个/的索引 const index = start.lastIndexOf('/') // 获取最后一个/后面的值 const val = start.substring(index + 1, start.length) // 判断是不是index结尾 if (val === 'index.js') { return start.substring(index, -1) } return str } console.log('directives', directives) export default { install (Vue) { Object.keys(directives).forEach((key) => { console.log('directives[key]', key, directives[key]) Vue.directive(key, directives[key]) }) } }

示例自定义指令页面:

src\directive\el-drag-dialog\index.js

/* * @Author: 周云芳 * @Date: 2022-06-28 15:11:03 * @LastEditors: 周云芳 * @LastEditTime: 2022-06-28 16:31:15 * @Description: 自定义指令示例 */ export default { inserted: function (el, binding) { el.addEventListener('click', () => { console.log('指令点点') }) } }

main.js引入

import Directive from '@/directive' Vue.use(Directive)

页面用使用:

<!-- * @Author: 周云芳 * @Date: 2022-06-28 09:18:44 * @LastEditors: 周云芳 * @LastEditTime: 2022-06-28 16:29:28 * @Description: 文件描述 --> <template> <div> 测试 <auto-test v-el-drag-dialog></auto-test> </div> </template> <script> export default { name: 'test', props: [''], data () { return {} }, } </script> <style lang="" scoped></style>

效果:

到此这篇关于vue2 对全局自定义指令一次性进行注册的文章就介绍到这了,更多相关vue全局自定义指令注册内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!



VUE 自定义 方法

需要 登录 后方可回复, 如果你还没有账号请 注册新账号
相关文章