vue2?對全局自定義指令一次性進行注冊的方法
更新時間:2022年06月29日 09:45:59 作者:周家大小姐.
這篇文章主要介紹了vue2?對全局自定義指令一次性進行注冊,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
在src下新建文件夾directive/index.js
index.js文件中用來寫入注冊方法
/* * @Author: 周云芳 * @Date: 2022-06-28 15:21:41 * @LastEditors: 周云芳 * @LastEditTime: 2022-06-28 16:44:16 * @Description: 用于自動注冊全局自定義指令 * 使用規(guī)則: * 根據導出的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全局自定義指令注冊內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue three.js創(chuàng)建地面并設置陰影實現示例
這篇文章主要為大家介紹了vue three.js創(chuàng)建地面并設置陰影實現示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-08-08