11

vue自定义指令

 3 years ago
source link: https://blog.csdn.net/weixin_47730573/article/details/112131494
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

自定义指令

自定义指令分为全局自定义指令和局部自定义指令

全局自定义指令注册:
html:

    <div id="app">
        <input type="text" v-focus >
    </div>
    Vue.directive("focus", {
        inserted: function (el) {

            el.focus();
            el.style.border = "4px solid pink"
        },
      
    }) 

局部自定义指令注册:
html代码同上
js:


    new Vue({
        el: "#app",
        directives:{
            focus:{
                inserted(el){
                    el.focus()
                    el.style.color='red'
                }
            }
        }
            

自定义指令一共有五个钩子函数
bind() 指令第一次绑定时调用 只调用一次
inserted() 被绑定元素被插入父节点是调用,
update() 被绑定元素所在模板更新时调用,不论绑定值是否发生变化
componentUpdated() 被绑定元素模板完成一次更新周期是调用
unbind() 指令与元素解绑是调用 只调用一次

输出的钩子函数的参数:
20210103093903218.png#pic_center
name 是自定义事件名
rawName 绑定方法


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK