天天看點

vue過濾器以及自定義指令vue 過濾器以及自定義指令

vue

過濾器以及自定義指令

過濾器

  • 私有過濾器
    • filters: {
          capitalize: function (msg) {
            return msg.replace('傻子', '**')
          }
        },
                 
  • 全局過濾器
    • Vue.filter('globalFilter', function (msg) {
        return msg.replace('傻逼', '**')
      })
                 
  • 使用:

    {{data name|filter name}}

自定義指令

  • 私有
    • directives: {
        focus: {
          inserted: function (el) {
            el.focus()
          }
        }
      }
                 
  • 全局
    • Vue.directive('focus', {
        bind: function (el) {
      
        },
        inserted: function (el) {
          // 聚焦元素
          el.focus()
        }
      })
                 
  • 在定義指令時不需要加

    v-

    ,在使用時需要加

    v-

  • 鈎子函數
    • bind

      :隻調用一次,指令第一次綁定到元素時調用
    • inserted

      :被綁定元素插入父節點時調用 ,僅保證父節點存在,但不一定已被插入文檔中
    • update

      :所在元件的

      VNode

      更新時調用,但是可能發生在其子

      VNode

      更新之前
  • 鈎子函數參數
    • el

      :指令所綁定的元素,可以用來直接操作 DOM
    • binding

      :包含以下屬性:
      • name

        :指令名,不包括

        v-

        字首。
      • value

        :指令的綁定值,例如:

        v-my-directive="1 + 1"

        中,綁定值為

        2

      • oldValue

        :指令綁定的前一個值,僅在

        update

        componentUpdated

        鈎子中可用。
      • expression

        :字元串形式的指令表達式。例如

        v-my-directive="1 + 1"

        中,表達式為

        "1 + 1"

      • arg

        :傳給指令的參數,可選。例如

        v-my-directive:foo

        中,參數為

        "foo"

      • modifiers

        :一個包含修飾符的對象。例如:

        v-my-directive.foo.bar

        中,修飾符對象為

        { foo: true, bar: true }