Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
youngwind opened this issue Aug 15, 2016 · 3 comments
Open

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

youngwind opened this issue Aug 15, 2016 · 3 comments
Labels

Comments

@youngwind
Copy link
Owner

youngwind commented Aug 15, 2016

前言

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 youngwind added the Vue label Sep 29, 2016
@cike8899
Copy link

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

@ZengTianShengZ
Copy link

// 注册一个全局自定义指令 `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
Copy link

Sphinm commented Jan 11, 2018

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants