Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

279
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda