youngwind / blog

梁少峰的个人博客
4.66k stars 385 forks source link

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

Open youngwind opened 7 years ago

youngwind commented 7 years ago

前言

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效果

cike8899 commented 7 years ago

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

ZengTianShengZ commented 6 years ago
// 注册一个全局自定义指令 `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);
  }
})
Sphinm commented 6 years ago

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