方式一
定义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()
}
})
}感谢大家观看,我们下期再见
It's not my first time to pay a visit this web page, i am visiting this website dailly and get good facts from here every day.
Hello, i think that i saw you visited my site so i got here to go back the want?.I'm trying to find things to improve my web site!I suppose its adequate to use a few of your concepts!!
Touche. Outstanding arguments. Keep up the great effort.
Wow, this post is good, my younger sister is analyzing these things, therefore I am going to let know her.
There's certainly a lot to learn about this topic. I like all the points you've made.
所有文章都令人印象深刻。由衷感谢 带来的灵感。
你 百分百 分享经验。坚持!
不常看到, 这么高质量的内容。谢谢。
@十二使徒岩 哪张图片?
照片令人惊艳。继续保持 心情。