Vue3.0自定义指令

自定义指令本质:使用JavaScript操作Dom元素

自定义指令使用

(1)定义

采用模块化定义,在src目录下创建directives目录,在这个目录中放置项目用到的所有自定义指令,方便管理和维护。

(2)注册

全局注册(使用较少)和局部注册

(3)页面使用

在html页面模板使用时,在定义的指令前加v-


Example1:页面加载输入框自动获取焦点

//App.vue
<template>
    <div>
        <h2>输入框自动获取焦点</h2>
        <input type="text" v-focus/>    //使用

        <h2>文本框高亮显示</h2>
        <p v-highlight="yellow">这段文字会高亮显示</p>

        <h2>导航条</h2>
        <div class="nav-bar" v-navCurrent="{
            curIdx,
            className:'nav-item',
            activeClass:'actice-item'}">
            <div class="nav-item" 
            v-for="(item,index) in state.items" 
            :key="index"
            :class="{'active-item':state.curIdx==index}"
            @click>
                {{item}}
            </div>
        </div>
    </div>
</template>

<script>
import focus from './directives/focus'    //导入
import highlight from './directives/highlight' 
import navCurrent from './directives/navcurrent' 
import {reactive} from 'vue'  

export default{
    name:'App',
    directives:{    //注册
        focus,
        highlight,
        navcurrent
    },
    setup(){
        const state=reactive({
            curIdx:0,
            items:["海鲜","羊肉","水果","蔬菜","鸡蛋"]
    })

    function itemClick(index){
        state.curIdx=index
    }
    return {
        state,
        itemClick
}
</script>
//directives目录下的focus.js
export default{    //导出默认对象
    mounted(el,binding,vnode){    //el:绑定的input
        el.focus()
}

Example2:文本高亮显示

//directives目录下的highlight.js
export default{
    mounted(el,binding,vnode){
        el.style.color=binding.value
    }
}

 Vue3.0自定义指令中的钩子函数

Vue3.0自定义指令中的钩子函数与以前的版本不兼容,vue3.0有以下几个钩子函数:

const MyDirective={
    beforeMount(el,binding,vnode,prevVnode){},
    mounted(){},
    beforeUpdate(){},    //新
    updated(){},
    beforeUnmount(){},    //新
    unmounted(){}
}

Example3:导航条

//directives目录下navcurrent.js
export default{
    mounted(el,binding,vnode){
        const ops=binding.value
        const navItem=el.getElementsByClassName(ops.className)
        navItem[ops.curIdx].classList.add(ops.activeClass)
    },
    updated(el,binding,vnode){
        const ops=binding.value
        const oldOps=binding.oldValue
        const navItem=el.getElementsByClassName(ops.className)
        navItem[oldOps.curIdx].classList.remove(ops.activeClass)
        navItem[ops.curIdx].classList.add(ops.activeClass)
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值