hjm-vue-directive

一个自定义指令库

Usage no npm install needed!

<script type="module">
  import hjmVueDirective from 'https://cdn.skypack.dev/hjm-vue-directive';
</script>

README

hjm-vue-directive

官方文档

介绍

  1. vue常用指令封装实现,既引既用

项目架构

.
|—— dist                      // 打包生成文件
|—— directive                 // 过滤器源码
|   |—— touch.js              // 手势指令
|   |—— load.js               // 加载指令
|   └── index.js              // 入口文件
|—— main.js                   // 开发demo入口
|—— index.js                  // 开发demo文件    
|—— .babelrc
|—— .eslintrc.js
|—— .gitignore                // 限制git上传文件
|—— .babelrc
|—— package.json              // 本地npm管理文件  
|—— JEST.md                   // 单元测试说明(暂时没有集成)
|—— CHANGELOG.md              // 更新日志
|—— README.md                 // 项目说明
|—— webpack.config.js         // 打包脚本
.

使用教程

  1. 安装npm包: npm i hjm-vue-directive

  2. 在项目中使用(如果不明白可以查看index实例demo)


//在main.js注入

// 1. 注入全部方法
import hjmvdirective from 'hjm-vue-directive'
Object.keys(hjmvdirective).forEach(key => {
  Vue.use(hjmvdirective[key])
})

// 2. 单个方法注入
import hjmvdirective from 'hjm-vue-directive'
Vue.use(hjmvdirective.touch).use(hjmvdirective.load)

// 在项目中使用过滤器
<p v-swipeleft='swipeleft'>我调用的是左滑动指令</p>
<p v-swiper='swiper'>我调用的是滑动指令</p>

// 在methods中写方法
methods: {
    swipeleft() {
        console.log('左滑动')
    },
    swiper() {
        // 通过event拿到坐标初始量和移动量
        console.log(event.starDis)
        console.log(event.moveDis)
        console.log('我是移动事件')
    }
}

开发说明

  1. lib目录里新建index.js文件为vue指令汇总文件
  2. 编写开发日常指令,必须按照规范
  3. 分类别区分指令文件
//------------------- 开发模板 -----------------//
const loadTypes = ['imgload'] // 指令名列表
class vueLoad { //指令类
  constructor(element, binding, type) {
    this.element = element
    this.binding = binding
    loadTypes.forEach(key => {
      if (type === key) {
        this[key]()
      }
    })
  }
  imgload() {}   // 指令方法
}
const Load = {}  // 注册自定义指令
Load.install = (Vue, optinons) => {
  loadTypes.forEach(key => {
    Vue.directive(key, {
      inserted: function(ele, binding) {
        new vueLoad(ele, binding, key)
      }
    })
  })
}
export default Load

  1. 效果测试与查看
  2. main.js里注册load
import hjmvdirective from './lib/index.js'
Object.keys(hjmvdirective).forEach(key => {
  Vue.use(hjmvdirective[key])
})

  1. index.html中测试

<p v-swiperight='swiperight'>我调用的是右滑动指令</p>

运行项目

  1. npm run dev 运行项目demo查看测试效果

方法总结

手势指令
指令 参数 备注
swipeleft fun:函数名(不用带括号) 左滑动
swiperight fun:函数名(不用带括号) 右滑动
swipedown fun:函数名(不用带括号) 下滑动
swipeup fun:函数名(不用带括号) 上滑动
longtap fun:函数名(不用带括号) 长按事件
swiper fun:函数名(不用带括号) 滑动事件(通过event拿到坐标初始量和移动量)
加载指令
指令 参数 备注
imgload 图片链接 图片加载(图片未完成加载前,用随机的背景色占位,图片加载完成后才直接渲染出来)