zoukankan      html  css  js  c++  java
  • 学习笔记:Vue——自定义指令

    在Vue2.0中,代码复用和抽象的主要形式是组件。然鹅,有的情况下,你仍然需要对普通DOM元素进行底层操作,这时候就会用到自定义指令。

    1.举个聚焦输入框的例子,全局注册focus指令

    Vue.directive('focus', {
      inserted: function (el) {
        el.focus()
      }
    })

    在模板中任何元素上使用自定义的指令 v-focus属性,如下:

    <input v-focus />

    当页面加载时,该元素将获得焦点(注意:autofocus在移动版Safari上不工作)

    2.自定义指令的各种钩子函数

    • bind:只调用一次,指令第一次绑定到元素时调用。在这里可以进行一次性的初始化设置
    • inserted:被绑定元素插入父节点时调用
    • ...

    3.钩子函数参数

    • el:指令所绑定的元素,可以用来直接操作DOM
    • binding:一个对象,包含以下属性:
      • name:指令名
      • value:指令的绑定值
      • oldValue:指令绑定的前一个值(尽在update和componentUpdated钩子中可用)
      • expression:字符串形式的指令表达式
      • arg:传给指令的参数
      • modifiers:一个包含修饰符的对象
    • vnode:Vue编译生成的虚拟节点。VNode API
    • oldVnode:上一个虚拟节点

    4.完整的自定义指令样例:

    <div id="hook-arguments-example" v-demo:foo.a.b="message"></div>
    Vue.directive('demo', {
      bind: function (el, binding, vnode) {
        var s = JSON.stringify
        el.innerHTML =
          'name: '       + s(binding.name) + '<br>' +
          'value: '      + s(binding.value) + '<br>' +
          'expression: ' + s(binding.expression) + '<br>' +
          'argument: '   + s(binding.arg) + '<br>' +
          'modifiers: '  + s(binding.modifiers) + '<br>' +
          'vnode keys: ' + Object.keys(vnode).join(', ')
      }
    })
    
    new Vue({
      el: '#hook-arguments-example',
      data: {
        message: 'hello!'
      }
    })

    (完)

    参考:Vue官方文档——自定义指令 https://cn.vuejs.org/v2/guide/custom-directive.html

  • 相关阅读:
    leetcode 350. Intersection of Two Arrays II
    leetcode 278. First Bad Version
    leetcode 34. Find First and Last Position of Element in Sorted Array
    leetcode 54. Spiral Matrix
    leetcode 59. Spiral Matrix II
    leetcode 44. Wildcard Matching
    leetcode 10. Regular Expression Matching(正则表达式匹配)
    leetcode 174. Dungeon Game (地下城游戏)
    leetcode 36. Valid Sudoku
    Angular Elements
  • 原文地址:https://www.cnblogs.com/cathy1024/p/10882871.html
Copyright © 2011-2022 走看看