项目场景:在每次提示框显示的时候让提示框中的输入框聚焦。一般情况下提示框是隐藏的。点击了编辑才会弹出。
在这里插入图片描述
在这里插入图片描述
使用vueuse useFocus 加载无效

<script setup lang="ts">
    import { ref } from 'vue';
    import { useFocus } from '@vueuse/core';
    import { Delete } from '@element-plus/icons-vue';

    defineProps<{
        title: string
    }>()
    
    const searchValue = ref('');
    const searchActive = ref(false);
    const input = ref();
    const { focused } = useFocus(input, {
        initialValue: true
    })

    const toggleSearch = async () => {
        searchActive.value = true;
        focused.value = true;
    }

    const closeSearch = () => {
        searchActive.value = false;
    }
</script>

<template>
    <div class="search-box">
        <div class="text flex-between" v-show="!searchActive">
            <span>{{ title }}</span>
            <span @click="toggleSearch()">搜索</span>
        </div>
        <div class="create flex-between" v-show="searchActive">
            <el-input ref="input" v-model="searchValue" type="text"/>
            <el-icon
                @click="closeSearch"
                color="red"
                size="16"
            >
                <Delete />
            </el-icon>
        </div>
    </div>
</template>

考虑到可能是 dom 更新之前就触发 focused 状态,因此添加 nextTick 之后再更新

import { nextTick, ref } from 'vue';
const toggleSearch = async () => {
        searchActive.value = true;
        await nextTick()
        focused.value = true;
    }

再次尝试还是不行。查看浏览器元素,发现input外面还包裹了一层,这应该就是问题所致点了。
在这里插入图片描述
使用原生input 替换el-input,就解决问题了。

<input ref="input" v-model="searchValue" type="text"/>

问题又来了,这个原生样式和element样式不一致,再去写一套样式多麻烦,再次阅读element文档。这不是提供了聚焦的方法吗,整的真麻烦,那只要在动态加载的时候触发这个方法不就OK了吗?
在这里插入图片描述

const toggleSearch = async () => {
        searchActive.value = true;
        // 拿到input元素,触发focus即可
        input.value.focus();
    }

问题解决。

tips:element 提供的 autofocus 原生属性 只会在页面加载时,并且 dom 存在加载一次,后续动态添加不生效,vueuse useFocus 也是对 input 的直接操作,像 el-input 外面还包裹一层 div 也会失效。

GitHub 加速计划 / eleme / element
10
1
下载
A Vue.js 2.0 UI Toolkit for Web
最近提交(Master分支:6 个月前 )
c345bb45 10 个月前
a07f3a59 * Update transition.md * Update table.md * Update transition.md * Update table.md * Update transition.md * Update table.md * Update table.md * Update transition.md * Update popover.md 10 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐