blog icon indicating copy to clipboard operation
blog copied to clipboard

如何编写一个vue自定义指令

Open youngwind opened this issue 7 years ago • 3 comments

前言

vue可以自定义指令,通过它可以做很多有趣的东西。比如vue-touch。官方的说明文档在这儿。 下面假设我要重写一个vue的绑定点击事件的指令,也就是说我要自己实现v-on:click。

源码

vue指令跟插件一样,是一个带有install方法的模块。

// index.js 
module.exports = {
    install: function (Vue) {
        Vue.directive('tap', {

            // 存储回调函数
            fn: null,

            bind () {
                // 做一些一次性的工作
            },

            update (fn) {
                if (typeof fn !== 'function') {
                    throw new Error('传给v-tap的参数不是一个函数,请检查');
                }

                this.fn = fn;
                this.el.addEventListener('click', this.fn);
            },

            unbind () {
                this.el.removeEventListener('click', this.fn);
            }
        });
    }
};

使用

// example.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>vue自定义点击指令demo</title>
</head>
<body>
<div id="app">
    <input type="text" name="user" v-model="user">
    <button v-tap="save">提交</button>
</div>
<script src="./example.js"></script>
</body>
</html>
// example.js

import Vue from 'vue';

import vTap from '../index';
Vue.use(vTap);

new Vue({
    el: '#app',
    data: {
        user: 'youngwind'
    },
    methods: {
        save () {
            console.log(this.user)
        }
    }
});

效果

v-tap效果

youngwind avatar Aug 15 '16 06:08 youngwind

这段代码在vue2.1里面已经不能正常使用了

cike8899 avatar Mar 27 '17 15:03 cike8899

// 注册一个全局自定义指令 `v-qclick`
Vue.directive('qclick', {
  bind (el, binding) {
    console.log('---bind---')
  },
  inserted(el, binding) {
    console.log('---inserted---')
    el.addEventListener('click', binding.value);

  },
  unbind (el, binding) {
    console.log('---unbind---')
    el.removeEventListener('click', binding.value);
  }
})

ZengTianShengZ avatar Jan 11 '18 08:01 ZengTianShengZ

我是用原生实现的事件发生器

Sphinm avatar Jan 11 '18 08:01 Sphinm