Vue 自定义指令

使用场景:

对普通DOM元素进行底层操作时,需要自定义指令。

功能一、 页面加载,不做任何操作,input获得焦点

template模板

<input v-focus />

自定义指令

directives: {
  focus: {
    // 指令的定义
    inserted: function (el) {
      el.focus()
    }
  }
}

功能二、给指令传参

template模板

<div v-demo="{ color: 'white', text: 'hello!' }"></div>

自定义指令

directives: {
 demo: {
    // 指令的定义
    function (el) {
      console.log(binding.value.color) // => "white"
      console.log(binding.value.text) // => "hello!"
    }
  }
}

原文地址:https://www.cnblogs.com/zero-zm/p/12102713.html