我就想用vue实现,只是两个人的聊天 同一个项目里
时间: 2024-03-12 14:46:41 浏览: 21
如果你只是想在同一个项目中实现两个人的聊天,可以考虑使用 Vue.js 自带的 `Event Bus` 实现消息的传递。具体步骤如下:
1. 创建一个 `Event Bus` 实例,在 `main.js` 中引入:
```js
import Vue from 'vue'
export const EventBus = new Vue()
```
2. 在聊天发送页面中,将发送的消息通过 `Event Bus` 发送出去,例如:
```js
import { EventBus } from '@/main.js'
export default {
methods: {
sendMessage() {
// 发送消息
const message = this.message
EventBus.$emit('message-sent', message)
// 清空输入框
this.message = ''
}
}
}
```
3. 在聊天接收页面中,通过 `Event Bus` 监听消息的到来,例如:
```js
import { EventBus } from '@/main.js'
export default {
data() {
return {
messages: []
}
},
created() {
// 监听消息
EventBus.$on('message-sent', message => {
this.messages.push(message)
})
}
}
```
这样,当发送页面发送消息时,接收页面就能够实时接收到消息并显示在页面上。需要注意的是,这种方式仅适用于同一个项目中的两个页面进行数据传递,如果需要多人聊天或者跨项目传递数据,则需要考虑使用其他技术方案。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)