vue3的自定义指令

一个小案例,input框获取焦点,默认实现

<input type="text" ref="input" name="" id="" />

import {ref,h,onMounted} from 'vue'

  setup(){
    const input  = ref(null);
    onMounted(()=>{
      input.value.focus();    //获取焦点
      console.log(input.value);
    })
    return{
      input
    }
  },

可以通过自定义指令来实现

1.局部指令   (当前文件内)

<input type="text" v-focus/>

export default {
  //自定义指令
  directives:{
    focus:{
      mounted(el,bindings,vnode,preVnode){   //在生命周期中操作
        el.focus()            //直接调用focus方法
      }
    }
  },
}

2.全局指令     (在main.js文件中定义)

//全局指令
app.directive('focus',{
  mounted(el,bindings,vnode,preVnode){
    el.focus()
  }
})

 

指令的生命周期

created: 在绑定元素的attribute 或事件监听器被应用之前调用

beforeMount,mounted,beforeUpdate,updated,beforeUnmount,unmounted

 

封装自定义指令的标准格式

1.创建规范的文件格式

 

 index文件为所有自定义指令的出口文件,传入app,(这里的app是在main.js中传入的)

 

 在main.js文件中

import registerDirectives from './views/direactives';

registerDirectives(app)

2.现在就可以在direactives中的format-time.js或者format-price.js文件中写相关逻辑代码

下面是一个格式化时间戳的小案例(format-time)

 

 3.需要使用该自定义组件时,如下操作

 

 基础的全局自定义组件的步骤到此结束了

posted @ 2022-02-20 20:22  无何不可88  阅读(329)  评论(0)    收藏  举报