VUE学习-自定义指令

自定义指令

有的情况下,你仍然需要对普通 DOM 元素进行底层操作,这时候就会用到自定义指令。

<div id="directive-demo">
	<input v-focus />
</div>
  • 全局注册

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

    new Vue({
    	el:'#directive-demo',
    	directives: {
    		focus: {
    			inserted: function (el) {
    				el.focus()
    			}
    		}
    	}
    })
    

指令钩子函数

  • bind:只调用一次,指令第一次绑定到元素时调用。在这里可以进行一次性的初始化设置。
  • inserted:被绑定元素插入父节点时调用 (仅保证父节点存在,但不一定已被插入文档中)。
  • update:所在组件的 VNode 更新时调用,但是可能发生在其子 VNode 更新之前。指令的值可能发生了改变,也可能没有。但是你可以通过比较更新前后的值来忽略不必要的模板更新 (详细的钩子函数参数见下)。
  • componentUpdated:指令所在组件的 VNode 及其子 VNode 全部更新后调用。
  • unbind:只调用一次,指令与元素解绑时调用。

<!-- //bind(el[,binding[,vnode[,oldVnode]]]) -->
<!--
// el: 指令所绑定的元素,可以用来直接操作 DOM(读写)。
// binding: {name, value, oldValue, expression, arg, modifiers}
/**
** name: 指令名,不包括 v- 前缀。
** value: 指令的绑定值, 绑定值为表达式时显示结果。如果指令需要多个值,可以传入一个 JavaScript 对象字面 ****量。记住,指令函数能够接受所有合法的 JavaScript 表达式。
** oldValue: 指令绑定的前一个值,仅在 update 和 componentUpdated 钩子中可用。
** expression: 字符串形式的指令表达式,绑定值为表达式时显示表达式。
** arg: 传给指令的参数。形式:v-my-directive:foo。
** modifiers: 一个包含修饰符的对象。
**** 例如: v-my-directive.foo.bar 中,修饰符对象为 { foo: true, bar: true }。
**/
// vnode: Vue 编译生成的虚拟节点。
//oldVnode: 上一个虚拟节点,仅在 update 和 componentUpdated 钩子中可用。-->

<div id="hook-args-demo" v-demo:foo.a.b="message"></div>
<script>
Vue.directive('demo', {
	bind: function (el, binding, vnode) {
		var s = JSON.stringify
		el.innerHTML = 'name: ' + s(binding.name) + '<br>' + 'value: ' + s(binding.value) + '<br>' + 'expression: ' + s(binding.expression) + '<br>' + 'argument: ' + s(binding.arg) + '<br>' + 'modifiers: ' + s(binding.modifiers) + '<br>' + 'vnode keys: ' + Object.keys(vnode).join(', ')
	}
})

new Vue({ 
	el: '#hook-args-demo',
	data: { message: 'hello!' }
})
</script>

image

函数简写

在很多时候,你可能想在 bind 和 update 时触发相同行为。

Vue.directive('color', function (el,binding) {
	el.style.backgroundColor = binding.value;
})

动态指令参数

指令的参数可以是动态的。例如,在 v-mydirective:[argument]="value" 中,argument 参数可以根据组件实例数据进行更新!

<div id="dynamicexample">
	<h3>Scroll down inside this section ↓</h3>
	<p v-pin:[direction]="200">I am pinned onto the page at 200px to the left</p>
</div>
<script>
Vue.directive('pin', {
	bind: function (el, binding, vnode) {
		el.style.position = 'fixed'
		el.style[binding.arg] = binding.value + 'px';
	}
})
new Vue({
	el: '#dynamicexample',
	data: function () {
		return {direction: 'left'}
	}
})
</script>
posted @ 2022-08-15 10:04  ~LemonWater  阅读(50)  评论(0编辑  收藏  举报