1、简介
设置文字超过限制长度后换行,换行后通过点击向上按钮切换到上一行,点击向下按钮切换到下一行,如果上一行或下一行没有文字则不切换,样式部分自行优化
本项目最终效果是这样
2、demo代码
<template>
<div>
<div class="text-container">
<div v-for="(line, index) in lines" :key="index" :class="['text-line', { 'active': index === currentLineIndex }]">
{{ line }}
</div>
</div>
<button @click="prevLine">上一行</button>
<button @click="nextLine">下一行</button>
</div>
</template>
<script>
export default {
data() {
return {
text: '这是一段很长很长的文本,需要进行换行展示。在这里我们可以通过 Vue 将其分解成多行,并通过点击按钮来切换展示不同的行。',
lines: [],
currentLineIndex: 0,
lineLength: 10 // 每行最大字符数
}
},
mounted() {
this.splitText(this.text);
},
methods: {
splitText(text) {
if (text.length > this.lineLength) {
const count = Math.ceil(text.length / this.lineLength);
for (let i = 0; i < count; i++) {
const start = i * this.lineLength;
const end = (i + 1) * this.lineLength;
const lineText = text.substring(start, end);
this.lines.push(lineText);
}
} else {
this.lines.push(text);
}
},
prevLine() {
const newIndex = this.currentLineIndex - 1;
if (newIndex >= 0 && this.lines[newIndex]) {
this.currentLineIndex = newIndex;
}
},
nextLine() {
const newIndex = this.currentLineIndex + 1;
if (newIndex < this.lines.length && this.lines[newIndex]) {
this.currentLineIndex = newIndex;
}
}
}
}
</script>
<style scoped>
.text-container {
width: 200px;
word-wrap: break-word;
white-space: pre-wrap;
}
.text-line {
display: none;
}
.text-line.active {
display: block;
}
</style>