Nuxt3问题:文本输入框的maxlength属性为何不生效?
Nuxt3中input的maxlength属性失效问题解决
问题描述
在Nuxt3开发过程中,为input输入框设置maxlength="70"属性后,仍能输入超过70个字符,属性未生效。问题输入框代码如下:
<input type="text" class="form-control" id="title" placeholder="title" v-model.trim="formData.title" required maxlength="70" aria-describedby="titleCount" />
完整页面代码:
<template> <section> <div class="card border-0"> <div class="row g-0"> <div class="col-lg-4"></div> <div class="col-lg-8"> <main class="card-body"> <form class="mt-3 mt-lg-0" @keydown.enter.prevent=""> <div class="form-floating mb-3"> <input type="text" class="form-control" id="title" placeholder="title" v-model.trim="formData.title" required maxlength="70" aria-describedby="titleCount" /> <div id="titleCount" class="form-text"> {{ titleLimit - formData.title.length }} characters remaining </div> <label for="title">Title</label> </div> </form> </main> </div> </div> </div> </section> </template> <script setup lang="ts"> const props = defineProps({ post: { type: Object, default: () => ({ caption: '', title: '', content: '', source: '', tags: [], imageFileName: '', imagePath: '', width: null, height: null, }), }, }); const formData = reactive({ ...props.post }); // Limit the number of title characters to 70 const titleLimit = computed(() => { const limit = 70; const titleLength = formData.title.length; return limit - titleLength; }); </script>
问题原因
问题根源在于v-model.trim修饰符。原生maxlength是基于输入框的原始输入值进行长度限制,但trim修饰符会让Vue在输入后自动去除首尾空格并更新绑定数据,这个过程会绕过原生的校验逻辑,导致输入框的实际显示值和绑定的数据不一致,最终让maxlength失效。
解决方法
方法一:移除v-model.trim,手动处理空格
去掉v-model上的trim修饰符,改为在合适时机手动处理首尾空格:
- 监听输入值变化实时处理:
watch(() => formData.title, (newVal) => { formData.title = newVal.trim(); }, { immediate: true });
- 或者在表单提交时统一处理:
const handleSubmit = () => { const submitData = { ...formData, title: formData.title.trim() }; // 执行表单提交逻辑 };
方法二:保留v-model.trim,手动限制长度
如果需要保留trim功能,可以通过监听输入值来手动限制最大长度:
watch(() => formData.title, (newVal) => { if (newVal.length > 70) { formData.title = newVal.slice(0, 70).trim(); } });
内容的提问来源于stack exchange,提问作者redshift
相关产品推荐
相关产品推荐

