一个聊天窗口,名字和聊天内容都在一行并且自动换行,使用rich-text无效果,代码如下,请问是我用法不对吗?
<template>
<view class="chat">
<scroll-view :style="'height:'+chatsHeight+'rpx;'" class="chat-body" scroll-y="true">
<view class="chat-line" v-for="(chat, id) in chats" :key="id">
<rich-text :nodes="formatChatNode(chat)"></rich-text>
</view>
</scroll-view>
<text class="chat-input-label">聊一聊</text>
</view>
</template>
<script>
export default {
data() {
return {
chats: [],
}
},
computed: {
chatsHeight() {
//一行16个字 计算总共聊天有多少行
let fontSize = 25;
let lineCount = 16;
let chats = this.chats;
let lineNum = 0;
for (let i in chats) {
let charCount = 0;
let chat = chats[i];
if (chat.name) {
charCount += chat.name.length;
} else {
charCount += 2;
}
if (chat.content) {
charCount += chat.content.length;
}
lineNum += parseInt(charCount/lineCount);
if (charCount%lineCount > 0) {
lineNum++;
}
}
let height = lineNum * fontSize;
console.log("============ " + lineNum + " " + height)
return height;
}
},
onLoad(pars) {
let chats = [];
let chat = {name: '小红', content: '想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥想聊啥'};
chats.push(chat);
let chat1 = {name: '小明大哥', content: '想聊啥想聊啥想聊啥'};
chats.push(chat1);
let chat2 = {name: '大英雄', content: '哈哈哈'};
chats.push(chat2);
this.chats = chats;
},
methods: {
formatChatNode(chat) {
let nodes = [];
if (chat.isNotice || '通知' === chat.name) {
let node = {type: 'text', attrs: {class:'chat-line-notice'}, text: '通知'};
nodes.push(node);
} else if (chat.name) {
let node = {type: 'text', attrs: {class:'chat-line-name'}, text: chat.name + ': '};
nodes.push(node);
}
if (chat.content) {
let node = {type: 'text', attrs: {class:'chat-line-text'}, text: chat.content};
nodes.push(node);
}
let chatNodes = [{name:'text', children: nodes}];
console.log("================= chatNodes " + JSON.stringify(chatNodes))
return chatNodes;
}
}
}
</script>
<style lang='scss' scoped>
.chat {
position: fixed;
bottom: 500rpx;
left: 20rpx;
width: 400rpx;
}
.chat-line {
background: rgba(11, 11, 11, 0.3);
padding: 20rpx;
border-radius: 15%;
margin-bottom: 10rpx;
display: flex;
color: #fff;
}
.chat-line-notice {
background: rgba(255, 255, 255, 0.8);
color: #a6a6a6;
text-align: center;
font-size: 30rpx;
}
.chat-line-name {
color: #9c9c9c;
font-size: 30rpx;
}
.chat-line-text {
color: #fff;
font-size: 30rpx;
}
.chat-input-label {
margin-top: 10rpx;
background: rgba(11, 11, 11, 0.3);
padding: 20rpx;
width: 170rpx;
height: 70rpx;
border-radius: 15%;
color: #a6a6a6;
font-size: 30rpx;
&:active {
opacity: 0.5;
}
}
</style>