很色h做游戏网站,aspmysql做网站,博客为什么用wordpress,网站建设公司设计网页的工具1、局部自定义指令
1.1 在script setup定义组件内的指令#xff0c;任何以v开头的驼峰式命名的变量都可以被用作一个自定义指令
templatedivh3使用自定义指令/h3div########################## start 局部自定义指令/d…1、局部自定义指令
1.1 在script setup定义组件内的指令任何以v开头的驼峰式命名的变量都可以被用作一个自定义指令
templatedivh3使用自定义指令/h3div########################## start 局部自定义指令/divdiv我是一个inputinput typetext v-myFocus //divdiv########################## end 局部自定义指令/div/div
/templatescript setup
import { ref, reactive } from vue
/*** 1、局部自定义指令 在模板中启用 v-focus* 在script setup定义组件内的指令任何以v开头的驼峰式命名的变量都可以被用作一个自定义指令* 为了区分下面全局自定义指令 v-focus这里全局改为v-MyFocus*/
// const vFocus {
// mounted: (el) el.focus()
// }
const vMyFocus {mounted: (el) el.focus()
}
/script
效果 1.2 如果是vue3的options api 自定义指令需要在directives选项中注册
templateinput v-focus /
/template
script
export default{setup() {},directives: {// 指令名focus: {// 生命周期mounted(el) {// 处理DOM的逻辑el.focus()},}}
}
/script 效果 2、全局自定义指令
2.1 创建文件 src/directives/focus.js
export default function(app) {app.directive(focus, {mounted(el) {console.log(focus指令 mounted)el.focus()},})
}
2.2 创建文件 src/directives/index.js
import registerFocus from ./focus // 获取焦点export default function registerDirectives(app) {registerFocus(app)
}
2.3 main.js中引入
import registerDirectives from ./directives/indexconst app createApp(App)
registerDirectives(app)报警告如下
index.vue:9 [Vue warn]: Failed to resolve directive: focus at Index onVnodeUnmountedfnonVnodeUnmounted refRef undefined at RouterView at App
2.4 页面内使用 div########################## start 全局自定义指令/divdiv我是一个使用全局自定义指令的inputinput typepassword v-focus //divdiv########################## end 全局自定义指令/div
效果 3、 常用的自定义指令后面有新的全局自定义指令封装会更新
3.1 input获取焦点
src/directives/focus.js
export default function(app) {app.directive(focus, {mounted(el) {console.log(focus指令 mounted)el.focus()},})
}
ts写法
// 获取焦点
export default function(app: any) {
app.directive(focus, {mounted(el: any) {console.log(focus mounted);el.focus();}})
}
3.2 防抖
src/directives/debounce.js
注册那一步和上面focus一样此处及后面将省略
// 防抖
export default function (app) {app.directive(debounce, {mounted(el, binding) {console.log(el, el, binding, binding);let timerel.addEventListener(click, () {if (timer) clearTimeout(timer)timer setTimeout(() {binding.value()}, 2000)})},})
}
ts写法
// 防抖
export default function(app: any) {app.directive(debounce, {mounted(el: any, binding: any) {let timer:anyel.addEventListener(click, () {if (timer) {clearTimeout(timer)}timer setTimeout(() {binding.value()}, 1000)})}})
}
使用
templatediv我是测试防抖的全局自定义指令,如果在该间隔内再次触发则重新计时。button classbtn v-debouncetestDebounceBtn 防抖按钮点击我2秒后执行一次/button/div
/templatescript setup/*** 3、防抖自定义指令 --- 全局*/
const testDebounceBtn () {console.log(防抖按钮点击我2秒内只执行一次)
}
/script
效果
点击按钮后2秒后执行2秒内再次触发点击将重新计时重新计时后2秒后才执行。正常开发时时间按照实际情况设定一般设定1秒后执行