如何为Vue Formulate动态表单的label添加80字符截断与展开功能
实现方案
核心思路是利用Vue Formulate自带的label插槽自定义渲染逻辑,无需修改原动态获取的表单项数据,单独维护展开状态即可实现需求。
步骤1:调整Vue实例逻辑
在原有data中新增expandedLabels对象存储每个表单项的展开状态,新增切换状态的方法:
Vue.use(VueFormulate) new Vue({ el: "#app", data () { return { expandedLabels: {}, // 新增:存储表单项展开状态 data: [ // 原有表单项数据保持不变 { validation: "accepted", type: 'checkbox', name: 'first', label: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.', }, { validation: "accepted", type: 'checkbox', name: 'second', label: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.', }, { validation: "accepted", type: 'checkbox', name: 'third', label: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.', } ] } }, methods: { // 新增:切换表单项展开状态 toggleExpand (name) { // 用$set保证动态新增属性的响应式生效 this.$set(this.expandedLabels, name, !this.expandedLabels[name]) } } })
步骤2:修改模板代码
给formulate-input添加label插槽,自定义渲染内容:
<script src="https://cdn.jsdelivr.net/npm/@braid/vue-formulate@2.4.1/dist/formulate.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <formulate-form> <formulate-input v-for="item in data" :key="item.name" v-bind="item" > <!-- 自定义label插槽 --> <template #label="{ label }"> <!-- 已展开或label长度不超过80时显示完整内容 --> <span v-if="expandedLabels[item.name] || label.length <= 80">{{ label }}</span> <!-- 未展开且长度超80时截断显示 --> <span v-else>{{ label.slice(0, 80) }}...</span> <!-- 长度超过80才显示切换按钮 --> <a v-if="label.length > 80" href="javascript:void(0)" @click="toggleExpand(item.name)" style="color: #1890ff; margin-left: 4px; cursor: pointer;" > {{ expandedLabels[item.name] ? '收起' : '阅读更多' }} </a> </template> </formulate-input> </formulate-form> </div>
步骤3:可选样式调整
如果需要统一管理按钮样式,可在原有css中添加以下规则,替换模板中的内联样式即可:
.formulate-label-toggle { color: #1890ff; margin-left: 4px; cursor: pointer; }
内容的提问来源于stack exchange,提问作者Marek
相关产品推荐
相关产品推荐

