zoukankan      html  css  js  c++  java
  • vue自定义指令

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style type="text/css">
            body, p, img, dl, dt, dd, ul, ol, h1, h2, h3, h4, h5, h6 { margin: 0; padding: 0; }
            body { position: relative; font: 12px/1.5 Simsun, Arial; }
            ul, ol { list-style: none; }
            img { border: 0 none; }
            input, select { vertical-align: middle; }
            table { border-collapse: collapse; }
            s, em, i { font-style: normal; text-decoration: none; }
            a { outline: none; text-decoration: none; }
            a:hover { text-decoration: underline; }
            .clear { *zoom: 1; }
            .clear:after { clear: both; content: "."; display: block; height: 0; overflow: hidden; visibility: hidden; zoom: 1; }
        </style>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.1/lodash.min.js"></script>
        <script src="https://unpkg.com/vue/dist/vue.js"></script>
    </head>
    <body>
    
    <div id="app">
        <input v-focus="1+1" v-focusss/>
    </div>
    
    <script type="text/javascript">
        Vue.directive('focus', {
            bind: function () {
                console.log('bind')
            },
            inserted: function (el, binding, vnode, oldVnode) {
                console.log('inserted')
                console.log(el, binding, vnode, oldVnode)
                el.focus()
            },
            update: function () {
                console.log('update')
            },
            componentUpdated: function () {
                console.log('componentUpdated')
            },
            unbind: function () {
                console.log('unbind')
            }
        })
    
        Vue.directive('focusss', {
            inserted: function (el) {
                el.blur()
            }
        })
    
        var v = new Vue({
            el: '#app'
        })
    </script>
    </body>
    </html>

    使用指令方法Vue.directive,创建自定义指令,第一个参数为自定义指令的名称,第二个参数为一个对象。

    这个对象里可以设置一些钩子函数,比如bind,inserted,update,componentUpdated,unbind

    函数对应一些参数,如el,binding,vnode,oldVnode等,

    然后在节点上设置该自定义指令v-*** 即可

    如果只需要bind和update钩子,函数也可以简写成下列形式:

    Vue.directive('color-swatch', function (el, binding) {
        el.style.backgroundColor = binding.value
    })

    也可以传入对象字面量

    <div v-demo="{ color: 'white', text: 'hello!' }"></div>
    Vue.directive('demo', function (el, binding) {
      console.log(binding.value.color) // => "white"
      console.log(binding.value.text)  // => "hello!"
    })
  • 相关阅读:
    Stream概念的理解
    nodejs进程间通信
    nodejs多进程spawn execFile exec fok方法的区别
    socket这个名词的理解
    Object.defineProperty方法总结
    git中HEAD^和HEAD~区别
    http常见的9种方法
    java怎么建立JAVA工程项目?
    树莓派mjpg-stream摄像头监控
    制作OS X 10.9 Mavericks 安装U盘
  • 原文地址:https://www.cnblogs.com/zhishaofei/p/6426472.html
Copyright © 2011-2022 走看看