im new to websockets and for my project im using Socket.io. what im trying to achive is having two taps and when a user clicks the button showDiv the div will be displayd to all connected users. i do have connection with server and i can see if a user is connected, but trying to implement my idea in vue is the hard stuff for me.
If you can help understand this i would appreciate it alot and thank you.
new Vue({
el:'#wrapper',
data:{
display: false,
joined: false,
},
methods:{
join() {
this.joined = true;
this.socketInstance = io("http://localhost:3000");
this.socketInstance.on(
"show", (data) => {
this.display = this.display(data);
}
)
},
show(){
const display = this.display
if (display == false) {
this.display = true
this.socketInstance.emit('showDiv', display)
}else {
this.display= false
}
},
},
mounted() {
this.join();
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="wrapper">
<h1 v-if="joined">We are connected</h1>
<h1 v-else>We are not connected</h1>
<button @click="show">Show/hide Div</button>
<div v-if="display" style="background-color: #4d00ff; width: 100px; height: 100px;"></div>
<div v-else>No div to see</div>
</div>
Node.js server
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = new Server(server, {
cors: {
origin: "*",
methods: ['GET', "POST"]
}
});
io.on('connection', (socket) => {
console.log(`user ${socket.id} is connected.`)
socket.on('message', data => {
socket.broadcast.emit('message:received', data)
})
socket.on('show', data =>{
socket.broadcast.emit('showDiv',data)
})
socket.on('disconnect', () => {
console.log(`user ${socket.id} left.`)
})
})
server.listen(3000, () => {
console.log('App server is running on 3000')
})