vue自定义指令

官网:https://cn.vuejs.org/v2/guide/custom-directive.html

 

var vm = new Vue({
    el: "#app",
    data: {},
    directives: {
        'focus': {
            inserted:function(el, binding,vnode,oldVnode) {
                console.log(el); // 就是input标签
                console.log(binding); // 对象: {name:"focus",rawName:"v-focus:ksbk.a.b",arg:"ksbk",expression:2,value:2,modifiers:{a:true,b:true}}
                el.focus();
            }
        }
    },
})
Vue.directive('focus',{
inserted:function (el) {
    console.log(el);
    el.focus();
}

var vm = new Vue({
    el: "#app",
    data: {},
})

注:指令要在new Vue()前面,要不然,报错!
eg:

[Vue warn]: Failed to resolve directive: focus

(found in )
钩子函数:

bind:只调用一次,指令第一次绑定到元素时调用。在这里可以进行一次性的初始化设置。
inserted:被绑定元素插入父节点时调用
update:
componentUpdated:
unbind:只调用一次,指令与元素解绑时调用。

钩子函数的参数:

el、binding、vnode、oldVnode

动态参数

Scroll down the page

I’ll now be offset from the left instead of the top

Vue.directive('tack', { update(el, binding, vnode) { el.style.position = 'fixed'; const s = (binding.arg == 'left' ? 'left' : 'top'); el.style[s] = binding.value + 'px'; } }) // start app new Vue({ el: '#app', data() { return { dynamicleft: 100 } }, methods:{ move:function(){ console.log("move"); this.dynamicleft=300; } } })
对象字面量

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

Vue.directive('demo', function (el, binding) { console.log(binding.value.color) // => "white" console.log(binding.value.text) // => "hello!" })

其他例子 eg:

  • 改变数据

its a custom directvie

new Vue({ el:"#app", data:{ count:0, }, methods:{ add(){ this.count++; }, }, directives:{ change:{ bind:function(el,binding){ console.log('指令已经绑定到元素了'); console.log(el); el.innerHTML=binding.value; }, update:function(el,binding){ console.log('指令的数据有所变化'); el.innerHTML=binding.value; if(binding.value==5){ console.log("if的判断执行"); } } } } })
  • 改变背景颜色
    默认给一个颜色,点击按钮的时候,颜色变化!

你可能感兴趣的:(vue-官网)