请在以上示例代码的基础上,使用if语句为聊天功能增加更多回复
时间: 2024-04-16 22:27:24 浏览: 18
当然,我可以为你添加更多的回复。以下是更新后的代码,增加了一些if语句来根据用户问题选择不同的回答:
```vue
<template>
<div class="chat-container">
<div class="chat-messages">
<div v-for="(message, index) in messages" :key="index" class="message">
<div v-if="message.from === 'user'" class="user-message">
{{ message.content }}
</div>
<div v-else class="ai-message">
{{ message.content }}
</div>
</div>
</div>
<div class="chat-input">
<input v-model="inputMessage" @keyup.enter="sendMessage" placeholder="请输入您的问题" />
<button @click="sendMessage">发送</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
inputMessage: '',
messages: []
}
},
methods: {
sendMessage() {
const userMessage = {
from: 'user',
content: this.inputMessage
}
this.messages.push(userMessage)
// 根据用户问题选择不同的回答
let aiMessage = {
from: 'ai',
content: ''
}
if (this.inputMessage.includes('你好')) {
aiMessage.content = '你好!有什么问题我可以帮助您解答?'
} else if (this.inputMessage.includes('天气')) {
aiMessage.content = '目前天气晴朗,温度为25°C'
} else if (this.inputMessage.includes('时间')) {
const currentTime = new Date().toLocaleTimeString()
aiMessage.content = `现在的时间是 ${currentTime}`
} else {
aiMessage.content = '抱歉,我暂时无法回答您的问题'
}
this.messages.push(aiMessage)
this.inputMessage = ''
}
}
}
</script>
<style scoped>
/* 样式代码省略,与之前示例相同 */
</style>
```
更新后的代码通过使用if语句根据用户的问题选择不同的回答。如果用户输入的问题包含"你好",则回复"你好!有什么问题我可以帮助您解答?";如果用户输入的问题包含"天气",则回复"目前天气晴朗,温度为25°C";如果用户输入的问题包含"时间",则回复当前时间;否则,回复"抱歉,我暂时无法回答您的问题"。
你可以根据需要自定义更多的回答,增加更多的if语句来匹配不同的问题,并提供相应的回复。希望这个更新后的代码对你有帮助!如果还有其他问题,请随时向我提问。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)