| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- <template>
- <view class="chat-page">
- <scroll-view class="chat-body" scroll-y :scroll-top="scrollTop">
- <view v-for="(msg, idx) in messages" :key="idx" class="msg-item" :class="msg.role">
- <view class="bubble">{{ msg.content }}</view>
- </view>
- </scroll-view>
- <view class="chat-input">
- <input class="input" v-model="inputText" placeholder="输入您的问题..." @confirm="send" confirm-type="send" />
- <button class="send-btn" size="mini" @click="send">发送</button>
- </view>
- </view>
- </template>
- <script>
- import { aiCoachSend } from '../../utils/api.js'
- export default {
- data() {
- return {
- inputText: '',
- messages: [],
- scrollTop: 0
- }
- },
- onLoad() {
- this.messages.push({
- role: 'assistant',
- content: '你好,我是你的减脂AI教练,请告诉我你的目标和当前情况,我会帮你制定合适的减脂计划。'
- })
- },
- methods: {
- scrollToBottom() {
- setTimeout(() => {
- this.scrollTop = this.messages.length * 1000
- }, 100)
- },
- send() {
- if (!this.inputText.trim()) return
- var content = this.inputText.trim()
- this.messages.push({ role: 'user', content: content })
- this.inputText = ''
- this.scrollToBottom()
- var payload = {
- content: content,
- history: this.messages.slice(0, -1).map(m => ({ role: m.role, content: m.content }))
- }
- aiCoachSend(payload).then(res => {
- if (res.data && res.data.response) {
- this.messages.push({ role: 'assistant', content: res.data.response })
- } else if (res.data && res.data.reply) {
- this.messages.push({ role: 'assistant', content: res.data.reply })
- } else {
- this.messages.push({ role: 'assistant', content: '抱歉,我暂时无法回答这个问题。' })
- }
- this.scrollToBottom()
- }).catch(() => {
- this.messages.push({ role: 'assistant', content: '网络异常,请稍后重试。' })
- this.scrollToBottom()
- })
- }
- }
- }
- </script>
- <style>
- .chat-page { display: flex; flex-direction: column; height: 100vh; background: #f8f8f8; }
- .chat-body { flex: 1; padding: 30rpx; box-sizing: border-box; }
- .msg-item { margin-bottom: 30rpx; display: flex; }
- .msg-item.user { justify-content: flex-end; }
- .msg-item.assistant { justify-content: flex-start; }
- .bubble { max-width: 70%; padding: 20rpx 30rpx; border-radius: 16rpx; word-wrap: break-word; }
- .user .bubble { background: #F97316; color: #fff; }
- .assistant .bubble { background: #fff; color: #333; }
- .chat-input { display: flex; padding: 20rpx 30rpx; background: #fff; border-top: 1rpx solid #eee; align-items: center; }
- .input { flex: 1; height: 80rpx; padding: 0 20rpx; background: #f5f5f5; border-radius: 40rpx; margin-right: 20rpx; }
- .send-btn { background: #F97316; color: #fff; border-radius: 40rpx; }
- </style>
|