vue 自定义指令
自定义指令:
1、全局指令:
(1)创建
Vue.directive('名称',{
钩子函数:function(el,binding){
el:dom对象
binding:指令对象,包含以下属性
name: 指令名,不包括 v- 前缀。
value:指令的绑定值,会进行动态解析,例如:v-my-directive="1 + 1" 中,绑定值为2。
oldValue:指令绑定的前一个值,仅在update和componentUpdated 钩子中可用,无论值是否改变都可用。
expression:字符串形式的指令表达式,不会动态解析,例如v-my-directive="1 + 1" 中,表达式为 "1 + 1"。
arg:传给指令的参数,可选,例如v-my-directive:foo中,参数为 "foo"。
modifiers:一个包含修饰符的对象,例如:v-my-directive.foo.bar中,修饰符对象为{ foo: true, bar: true }。
vnode: Vue编译生成的虚拟节点,移步 VNode API 来了解更多详情。
oldVnode: 上一个虚拟节点,仅在 update 和 componentUpdated 钩子中可用。
除了el之外,其它参数都应该是只读的,切勿进行修改,如果需要在钩子之间共享数据,建议通过元素的 dataset 来进行。
}
})
其中钩子函数:
(1)bind:只调用一次,指令第一次绑定到元素时调用,在这里可以进行一次性的初始化设置。
(2)inserted:被绑定元素插入父节点时调用 (仅保证父节点存在,但不一定已被插入文档中)
(3)update:所在组件的 VNode 更新时调用,但是可能发生在其子 VNode 更新之前,指令的值可能发生了改变,也可能没有,但是你可以通过比较更新前后的值来忽略不必要的模板更新
(4)componentUpdated:指令所在组件的 VNode 及其子 VNode 全部更新后调用。
(5)unbind:只调用一次,指令与元素解绑时调用。
(2)支持动态参数
<p v-pin:[direction]="200">...</p>
Vue.directive('pin', {
bind: function (el, binding, vnode) {
el.style.position = 'fixed'
var s = (binding.arg == 'left' ? 'left' : 'top') binding.arg获取:后的参数
el.style[s] = binding.value + 'px'
}
})
(3)函数简写
bind和update时触发相同行为
Vue.directive('color-swatch', function (el, binding) {
el.style.backgroundColor = binding.value
})
2、局部指令
在组件中和data同级
directives:{
名称:{
钩子函数
}
}
代码示例:
main.js:
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
Vue.config.productionTip = false
//自定义全局指令
Vue.directive('focus',{
inserted:function(el,binding,vnode,oldnode){
el.focus();
}
})
Vue.directive('li',{
inserted:function(el,binding,vnode,oldnode){
console.log(binding)
console.log(binding.modifiers)
let str='<ul>'
for(let i=0;i<binding.value.length;i++)
{
str+=`<li>${ binding.value[0]}</li>`
}
str+='</ul>';
el.innerHTML=str;
}
})
/* eslint-disable no-new */
new Vue({
el: '#app',
data:{ foo:'hello foo'},
components: { App },
template: '<App/>'
})
组件:
<template>
<div>
<input type='text' v-focus v-local/>
</div>
</template>
<script>
export default{
name:'d',
data()
{
return{
}
},
//自定义局部指令
directives:{
local:{
bind(el)
{
el.value='jeff'
console.log('局部一次')
}
}
}
}
</script>
<style lang="css">
</style>
指令参数测试:
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-arguments-example',
data: {
message: 'hello!'
}
})
还没有评论,来说两句吧...