这次我们写一个vue3.2版本自定义指令是如何来使用的,就写一个简单的input框自动获取焦点的案例
1.在src目录下新建一个directive文件,在此文件夹下新建一个index.js文件夹,接着输入如下内容
const directives = (app) => {
app.directive('focus',{
mounted(el) {
el.focus()
}
})
}
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'
</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>
const vFocus = {
mounted(el) {
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) {
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>