Vue 自定义指令

 

自定义指令

何时调用?
指令所在的模板被解析时(如初次渲染,以及后续模板更新)

函数式
在vm实例的directives属性中,可以拿到element和bindings两个形参

对象式

  • bind 指令与元素建立联系
  • inserted 指令插入到页面
  • update 指令所在模板更新时调用

指令函数中的this全部指向window

全局指令

Vue.directive(name,{
    bind(){},
    inserted(){},
    update(){}
})

命名
不推荐驼峰,多个单词建议用-连接

demo

实现v-big与v-fbind

    <div id="root">
        <!-- 内置指令 -->
        初始:<span>{{value}}</span>
        现在:<span v-big="value"></span>
        <button @click="value++">新增</button>
        <input type="text" v-fbind>
    </div>
    <script>
        const vm = new Vue({
            el: "#root",
            data: {
                value: 0
            },
            directives: {
                big: (element, bindings) => element.innerText = bindings.value << 4,
                fbind: {
                    bind: (element, bindings) => {
                        element.value = 1
                    },
                    inserted: (element, bindings) => {
                        element.focus()
                    },
                    update: (element, bindings) => {
                        element.focus()
                    }
                }
            }
        })
    </script>
posted @   IslandZzzz  阅读(32)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示