vue自定义指令

本文深入探讨了Vue框架中自定义指令的使用方法,包括全局和局部指令的创建与应用,通过实例展示了如何利用自定义指令增强Vue组件的功能,特别关注了指令的生命周期钩子及其在实际场景中的运用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vue自定义指令

  1. 内置指令

​ v-html

v-text

v-on

v-bind

v-if

v-else-if

v-else

v-show

v-for

v-model

v-slot 【 2.6.x 】

  1. 自定义指令:案列
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="../vue.js"></script>
</head>
<body>
    <div id="app">
        <button @click = "flag=false">删除</button>
       <input type="text" password = "请输入" v-focus = "'你好'" v-if = "flag">
    </div>
</body>
<script>

    Vue.directive('focus',{
        bind(){
            console.log('bind')
        },
        inserted(el,binding,vnode,oldvnode){
            console.log('el',el)//指令绑定的元素
            console.log('binding',binding )//保存指令的所有信息
            if(binding.modifiers.a){
                el.style.background = "pink"
            }else{
                el.style.background = "blue"
            }
            console.log('vnode',vnode)
            console.log('oldVnode',oldvnode)
            el.focus()//获取焦点
        },
        unbind(){
            console.log('unbind')//点击删除按钮会触发
        }
    })
    new Vue({
        el:'#app',
        data:{
            flag:true
        }
    })
</script>
</html>
  1. 自定义指令:局部
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="../vue.js"></script>
</head>
<body>
    <div id="app">
        <input type="text" name="" id="" v-focus>
    </div>
</body>
<script>
    new Vue({
        el:"#app",
        directives:{
            'focus':{
                inserted(el){
                    el.focus()
                }
            }
        }
    })
</script>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值