标签导航:

vant input组件:如何仅在输入框聚焦时显示字数限制?

Vant Input组件:巧妙实现聚焦状态下显示字数限制

Vant框架的van-field组件默认始终显示字数限制,但这并非所有场景的理想选择。本文将演示如何仅在输入框获得焦点时显示剩余字数。

核心在于根据输入框的焦点状态动态控制字数限制信息的显示与隐藏。 由于Vant本身不提供此功能,我们需要借助Vue.js的特性。

解决方案:利用Vue计算属性和事件监听器。

我们创建一个计算属性showWordLimit,其值取决于输入框的焦点状态。当输入框聚焦时,showWordLimit为true,显示字数限制;失去焦点时,showWordLimit为false,隐藏字数限制。

代码示例:

<template>
  <van-field v-model="inputValue" @focus="onFocus" @blur="onBlur">
    <template #suffix>
      <span v-if="showWordLimit">{{ remainingChars }}字</span>
    </template>
  </van-field>
</template>

<script>
import { ref, computed } from 'vue';
import { Field } from 'vant';

export default {
  components: {
    'van-field': Field
  },
  setup() {
    const inputValue = ref('');
    const isFocused = ref(false);
    const maxLength = 10; // 字数限制

    const remainingChars = computed(() => maxLength - inputValue.value.length);
    const showWordLimit = computed(() => isFocused.value);

    const onFocus = () => { isFocused.value = true; };
    const onBlur = () => { isFocused.value = false; };

    return { inputValue, remainingChars, showWordLimit, onFocus, onBlur };
  }
};
</script>

代码解释:

  • 使用@focus和@blur事件监听输入框的焦点变化,更新isFocused的值。
  • showWordLimit计算属性根据isFocused的值决定是否显示字数限制。
  • 使用v-if指令根据showWordLimit的值条件性地渲染字数限制信息。 我们使用#suffix插槽将字数限制信息显示在输入框的后面。

通过以上方法,我们成功地实现了仅在输入框聚焦时显示字数限制的功能,提升了用户体验。