自定义指令directive

// 注册一个全局自定义指令 `v-focus`
Vue.directive('focus', {
  // 当被绑定的元素插入到 DOM 中时……
  inserted: function (el) {
    // 聚焦元素
    el.focus()
  }
})

如果想注册局部指令,组件中也接受一个 directives 的选项:

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

然后你可以在模板中任何元素上使用新的 v-focus property,如下:

<input v-focus>

//例子
<template>
  <div>
    <div v-hello="red">注:这是红色</div>
    <div v-hello="green">注:这是绿色</div>
  </div>
</template>
<script>
// import Vue from 'vue'
// Vue.directive("hello",function(el,binding,vnode){
//        el.style["color"]= binding.value;
//     })
export default {
  name: 'Element',
  data() {
    return {
      red:"red",
      green:'green'
    }
  },
  directives:{
      hello:function(el,binding,vnode){
        console.log(el,binding,vnode)
          el.style["color"]= binding.value;
      }
    }
}
</script>
 
原文地址:https://www.cnblogs.com/hellofangfang/p/13560003.html