# 15.自定义指令

# 1.为何需要自定义指令

  • 内置指令不能满足我们特殊的需求

  • Vue允许我们自定义指令

# 2.自定义指令的语法规则 (获取元素焦点)

Vue.directive('focus' {
  inserted: function(el) {
	// 获取元素的焦点
	el.focus();
 }
})
1
2
3
4
5
6

# 3.自定义指令用法

<input type="text" v-focus>
1

# 4.带参数的自定义指令

# 1).改变元素背景色

Vue.directive('color', {   // action是指令的名称
  inserted: function(el, binding) {
    // inserted 是一个函数, 会在特定的时机进行调用, 什么时机? 这个元素插入到dom节点时会调用
    // el 当前使用指令的元素
    // binding 是自定义的 通过binding得到指令后面的数据
    el.style.backgroundColor = binding.value.color;
  }
 }
})
1
2
3
4
5
6
7
8
9

# 2).指令的用法

<input type="text" v-color='{color: "orange"}'>
1

# 5.局部指令

  • 局部指令,需要定义在 directives 的选项 用法和全局用法一样
  • 局部指令只能在当前组件里面使用
  • 当全局指令和局部指令同名时以局部指令为准
<input type="text" v-color='msg'>
 <input type="text" v-focus>
 <script type="text/javascript">
    /*
      自定义指令-局部指令
    */
    var vm = new Vue({
      el: '#app',
      data: {
        msg: {
          color: 'red'
        }
      },
   	  //局部指令,需要定义在  directives 的选项
      directives: {
        color: {
          bind: function(el, binding){
            el.style.backgroundColor = binding.value.color;
          }
        },
        focus: {
          inserted: function(el) {
            el.focus();
          }
        }
      }
    });
  </script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
上次更新: 2020/10/27 下午11:58:10