Vue学习—深入剖析自定义指令

一、自定义指令

1.简介

我们可以自己写一个自定义指令去操作DOM元素,以达到代码复用的目的。注意,在 Vue 中,代码复用和抽象的主要形式是组件。然而,有的情况下,你仍然需要对普通 DOM 元素进行底层操作,这时候就会用到自定义指令。

全局注册指令:

Vue.directive('focus', {/** */})

局部注册指令

const vm = new Vue({
  el: '#app',
  directives: {
    focus: {/** */}
  }
})

使用:

<input v-focus></input>

例如,写一个自动聚焦的输入框:

<div id="app">
    <!-- <input type="text" v-focus> -->
    <my-input></my-input>//只能同时对焦一个哦
</div>
<script>
    Vue.directive('focus',{
        inserted: function(el){
            el.focus();
        }
    });
    Vue.component('my-input',{
        template: `
            <input type='text' v-focus>
        `
    });
    const vm = new Vue({
        el: '#app',
        data: {

        }
    });
</script>

此时,在input元素上使用 v-focus 指令就可以实现自动聚焦了。

2.钩子函数

自定义指令对象提供了钩子函数供我们使用,这些钩子函数都为可选。

1.bind

只调用一次,指令第一次绑定到元素时调用。在这里可以进行一次性的初始化设置。

2.inserted

被绑定元素插入父节点时调用(仅保证父节点存在,但不一定已被插入文档中)。

3.update

所在组件的 VNode 更新时调用,但是可能发生在其子 VNode 更新之前

4.componentUpdated

指令所在组件的 VNode 及其子 VNode 全部更新后调用。

5.unbind

只调用一次,指令与元素解绑时调用(被绑定的Dom元素被Vue移除)。

<div id="app">
    <my-input :name='name' v-if='show'></my-input>
</div>
<script>
    Vue.directive('focus',{
        bind () {
            console.log('bind');
        },
        inserted (el) {
            // el.focus();
            console.log('inserted');
        },
        update () {
            console.log('update');
        },
        componentUpdated () {
            console.log('componentUpdated');
        },
        unbind() {
            console.log('unbind');
        }
    });
    Vue.component('my-input',{
        props: ['name'],
        template: `
            <input type='text' v-focus="name">
        `
    });
    const vm = new Vue({
        el: '#app',
        data: {
            name: 'jimo',
            show: true
        }
    });
</script>

在这里插入图片描述

3.钩子函数参数

  • el: 指令所绑定的元素,可以用来直接操作DOM。

  • binding:对象,包含以下属性:

    • name:指令名,不包括 v- 前缀。
    • value:指令的绑定值,例如:v-focus="name" 中,绑定值为 'jimo'
    • oldValue:指令绑定的前一个值,仅在 update 和 componentUpdated 钩子中可用。无论值是否改变都可用。
    • expression:字符串形式的指令表达式。例如 v-focus="1 + 1" 中,表达式为 "1 + 1"
    • arg:传给指令的参数,可选。例如 v-focus:src 中,参数为 "src"
    • modifiers:一个包含修饰符的对象。例如:v-focus:src.x.y 中,修饰符对象为 { x: true, y: true }
  • vnode:Vue 编译生成的虚拟节点。
    在这里插入图片描述

  • oldVnode:上一个虚拟节点,仅在 update 和 componentUpdated 钩子中可用。

4.练习

1.模拟 v-show

// 绑定的值为false,display为none,值为true,display为""
Vue.directive('myshow',{
    bind(el,binding){
        const { value } = binding;
        const display = value ? '' : 'none';
        el.style.display = display;
    },
    update(el,binding){
        const { value } = binding;
        const display = value ? '' : 'none';
        el.style.display = display;
    }
});

2.模拟 v-model

// 1. 通过绑定的数据,给元素设置value
// 2. 当触发input事件时,去更改数据的值
// 3. 更改数据后,同步input的value值
Vue.directive('mymodel', {
  bind (el, binding, vnode) {
    const vm = vnode.context;
    const { value, expression } = binding;
    el.value = value;

    el.oninput = function (e) {
      const inputVal = el.value;
      vm[expression] = inputVal;
    }
  },
  update (el, binding) {
    const { value } = binding;
    el.value = value;
  },
})

3.写一个 v-slice(截取文本框)

<div id="app">
    <input type="text" v-slice:7.number='name'>
    <!-- <my-input :name='name'></my-input> -->
    {{ name }}

</div>
<script>
	Vue.directive('slice', {
	    bind (el, binding, vnode) {
	    	const vm = vnode.context;
	    	let { value, expression, arg, modifiers } = binding;

	    	if(modifiers.number) {
	      		value = value.replace(/[^0-9]/g, '');
	    	}

	    	el.value = value.slice(0, arg);
	    	vm[expression] = value.slice(0, arg);

	    	el.oninput = function (e) {
	      		let inputVal = el.value;

 	     		if(modifiers.number) {
 	       			inputVal = inputVal.replace(/[^0-9]/g, '');
 	     		}

	      		el.value = inputVal.slice(0, arg);
	      		vm[expression] = inputVal.slice(0, arg);
	    	}
	  },
	  update (el, binding, vnode) {
	    	const vm = vnode.context;
	    	let { value, arg, expression, modifiers } = binding;

	    	if(modifiers.number) {
	      		value = value.replace(/[^0-9]/g, '');
	    	}

	    	el.value = value.slice(0, arg);
	    	vm[expression] = value.slice(0, arg);
	  	},
	});
    const vm = new Vue({
        el: '#app',
        data: {
            name: 'jimohuabukai',
            show: true
        }
    });
</script>

在这里插入图片描述

4.动态指令参数

指令的参数可以是动态的。如:v-directive:[arguments]="valueargument参数可以根据组件实例数据进行更新。(此时要在update中监听改变argument后)

重写 v-slice

Vue.directive('slice', {
  bind (el, binding, vnode) {
    const vm = vnode.context;
    let { value, expression, arg, modifiers } = binding;

    if(modifiers.number) {
      value = value.replace(/[^0-9]/g, '');
    }

    el.value = value.slice(0, arg);
    vm[expression] = value.slice(0, arg);

    el.oninput = function (e) {
      let inputVal = el.value;

      if(modifiers.number) {
        inputVal = inputVal.replace(/[^0-9]/g, '');
      }

      el.value = inputVal.slice(0, arg);
      vm[expression] = inputVal.slice(0, arg);
    }
  },
  update (el, binding, vnode) {
    const vm = vnode.context;
    let { value, arg, expression, modifiers } = binding;
    
    if(modifiers.number) {
      value = value.replace(/[^0-9]/g, '');
    }

    el.value = value.slice(0, arg);
    vm[expression] = value.slice(0, arg);

    el.oninput = function (e) {
      let inputVal = el.value;

      if(modifiers.number) {
        inputVal = inputVal.replace(/[^0-9]/g, '');
      }

      el.value = inputVal.slice(0, arg);
      vm[expression] = inputVal.slice(0, arg);
    }
  }
});

5.函数简写

当想在 bind 和 update 中触发相同行为,而不关心其他钩子时,可以写成函数的形式:

Vue.directive('myshow', (el, binding) => {
  const { value } = binding;
  const display = value ? '' : 'none';
  el.style.display = display;
});
Vue.directive('slice', (el, binding, vnode) => {
  const vm = vnode.context;
  let { value, expression, arg, modifiers } = binding;

  if(modifiers.number) {
    value = value.replace(/[^0-9]/g, '');
  };

  el.value = value.slice(0, arg);
  vm[expression] = value.slice(0, arg);

  el.oninput = function (e) {
    let inputVal = el.value;

    if(modifiers.number) {
      inputVal = inputVal.replace(/[^0-9]/g, '');
    };

    el.value = inputVal.slice(0, arg);
    vm[expression] = inputVal.slice(0, arg);
  }
});

6.对象字面量

如果自定义指令需要多个值,可以传入一个 JS 对象字面量。指令函数能够接受所有合法的 JS 表达式。

<div v-demo="{ color: 'white', text: 'hello!' }"></div>
Vue.directive('demo', function (el, binding) {
  console.log(binding.value.color) // => "white"
  console.log(binding.value.text)  // => "hello!"
});
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飞羽逐星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值