8.vue3.2自定义全局指令,局部指令+实战小demo+防抖优化

这次我们写一个vue3.2版本自定义指令是如何来使用的,就写一个简单的input框自动获取焦点的案例
1.在src目录下新建一个directive文件,在此文件夹下新建一个index.js文件夹,接着输入如下内容
const directives =  (app) => {
  //这里是给元素取得名字,虽然是focus,但是实际引用的时候必须以v开头
  app.directive('focus',{
    //这里的el就是获取的元素
    mounted(el) {
      el.focus() 
     }
  })
}

//默认导出 directives
export default directives
2.在全局注册directive
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import directives from './directives'

const app = createApp(App)
directives(app)

app.use(store).use(router).mount('#app')
3.在你需要的页面进行自定义指令的使用
<template>
  <div class="container">
    <div class="content">
      <input type="text"  v-focus>
      内容
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
// const vMove:Directive = () =>{

// }
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  .content {
    border-top: 5px solid black;
    width: 200px;
    height: 200px;
    cursor: pointer;
    border-left: 1px solid #ccc;
    border-right: 1px solid #ccc;
    border-bottom: 1px solid #ccc;
  }
}
</style>

好了,就这样,一个全局的自定义指令就实现了
既然全局的自定义指令都来了,那么局部自定义指令肯定不能少,这次我们写一个小demo,进去页面自动获取焦点,然后让盒子的颜色根据你input框输入的内容变色,并且作防抖处理,都是干货呀
在vue3.2setup语法糖模式下,自定义指令变得及其简单
<input type="text" v-model="value" v-focus>

<script setup>
//直接写,但是必须是v开头
const vFocus = {
  mounted(el) {
    // 获取input,并调用其focus()方法
    el.focus()
  }
}
</script>
这样就实现了,接下来我们做一个我开头说的小demo吧
<template>
  <div class="container">
    <div class="content" v-move="{ background: value }">
      内容
      <input type="text" v-model="value" v-focus @keyup="see">
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
const value = ref('')

const vFocus = {
  mounted(el) {
    // 获取input,并调用其focus()方法
    el.focus()
  }
}

let timer = null

const vMove = (el, binding) => {
  if (timer !== null) {
    clearTimeout(timer)
  }
  timer = setTimeout(() => {
    el.style.background = binding.value.background
    console.log(el);
  }, 1000);
}

</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;

  .content {
    border-top: 5px solid black;
    width: 200px;
    height: 200px;
    cursor: pointer;
    border-left: 1px solid #ccc;
    border-right: 1px solid #ccc;
    border-bottom: 1px solid #ccc;
  }
}
</style>

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值