Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

280
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda