Skip to content

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

Open
@youngwind

Description

@youngwind

前言

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions