方式一
定义ref绑定到input中, 调用focus
<template>
<div class="app">
<input type="text" ref="inputRef">
</div>
</template>
<script setup>
// 1.方式一: 定义ref绑定到input中, 调用focus
import useInput from "./hooks/useInput";
const { inputRef } = useInput();
</script>
<style lang="less" scoped>
</style>其中,src的/hooks/useInput.js文件
import { ref,onMounted } from 'vue';
export default function useInput(){
const inputRef = ref()
onMounted(()=>{
inputRef.value?.focus()
})
return { inputRef }
}方式二:自定义指令(局部指令)
Composition-API
<template>
<div class="app">
<input type="text" v-focus>
</div>
</template>
<script setup>
// 2.方式二:自定义指令(局部指令)
const vFocus = {
// 生命周期的函数(自定义指令)
mounted(el){
console.log("v-focus应用的元素被挂载了")
el?.focus();
}
}
</script>
<style lang="less" scoped>
</style>Options Api写法
<template>
<div class="app">
<input type="text" v-focus>
</div>
</template>
<script>
export default{
directives:{
focus:{
// 生命周期的函数(自定义指令)
mounted(el){
// console.log("v-focus应用的元素被挂载了", el)
el?.focus()
}
}
}
}
</script>
<style lang="less" scoped>
</style>方式三:自定义指令(全局指令)
使用app.directive()函数,在main.js文件中修改
import { createApp } from 'vue'
import App from './01_自定义指令/App.vue'
const app = createApp(App);
app.directive("focus",{
// 生命周期的函数(自定义指令)
mounted(el){
console.log("v-focus应用的元素被挂载了",el)
el.focus();
}
})
app.mount('#app')
当然我们把所有自定义元素都放在main.js中显得太乱了,所以我们可以将它抽离出来
// main.js
import { createApp } from 'vue'
import App from './01_自定义指令/App.vue'
import useDirectives from './01_自定义指令/directives/index'
const app = createApp(App);
// app.directive("focus",{
// // 生命周期的函数(自定义指令)
// mounted(el){
// console.log("v-focus应用的元素被挂载了",el)
// el.focus();
// }
// })
// 自定义指令方式一:
useDirectives(app)
app.mount('#app')引入的文件
// directives/index.js
import directiveFocus from "./focus"
export default function directives(app) {
directiveFocus(app)
}
// directives/focus.js
export default function directiveFocus(app) {
app.directive("focus", {
// 生命周期的函数(自定义指令)
mounted(el) {
// console.log("v-focus应用的元素被挂载了", el)
el?.focus()
}
})
}感谢大家观看,我们下期再见
我热爱 旅游专栏。令人惊艳了解路线。
欣赏你的照片, 我明白, 世界很美。感谢 旅行灵感。
读起来像小说。继续保持 带来的灵感。
让人精神焕发的 帖子! 我准备订票了。
以后焦虑了或者迷茫了记得回来看看
我非常喜欢 出行博客。鼓舞人心查看路线。
你们的博客 百分百 帮助选择路线。坚持!
信息丰富的 出行资源! 越来越棒!
My brother suggested I might like this blog. He was entirely right. This post actually made my day. You cann't imagine just how much time I had spent for this information! Thanks!
我热爱, 写得很实在。你的博客 就是 最好的例子。很出色。