Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

278
Views
how to call a function on every open page using node.js vue.js and socket.io

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')
})

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!