Specify a file for Node.JS (vue)

So, I am wondering how I can add another JavaScript file as it is. Very similar to PHP includefunction / keyword. I am not looking for a function export, as this allows you to use variables from other files.

I use vue init webpack my-project.

Here I basically have (Vue):

mounted () {
    socket = io("http://localhost:8081")
    socket.connect()

    // ensure server has actually put us in a room
    socket.on("find game", () => {
        this.gameSearch = "finding"
    })
    ...
}

So basically I have a whole bunch socket.onthat I would like to move to another file. I am wondering how I could turn them on so that they work as if the code was already inserted there (e.g. PHP include)


How it might look at the end:

mounted () {
    <socket.js file>
}

socket.js

socket = io("http://localhost:8081")
socket.connect()

// ensure server has actually put us in a room
socket.on("find game", () => {
    this.gameSearch = "finding"
})
...
+6
source share
3 answers

, , , , , , bable es6, vue js , .

, , . {, inline ) ( , , - :))

, , bundle.js

, , coed , , , .

, es6, bable

: code.js, main.js (main.js) , .., code.js

code.js/ socket.js

const code = function() {

    // this whole space is your's

    console.log(this);

    console.log(this.socket);

    const test = () => {
        console.log(this);
    }

    test()
}
export default code

my main.js/ vue

import socketCode from './code';

const main = {
    socket: 'test',
    init() {
        console.log(this);
        let socketCodebinded = socketCode.bind(this); // magical this binding
        socketCodebinded(); // this will do all event-binding things 
        //and good thing is that it will have "this" as context so no breaking of references

        ... continue other code or add another lib ;) like above
    }
}

main.init();

/, code.js/socket.js , main.js.

+5

, , . socket.on , .

sockets.js

  function attachSockets($socket, $this){ // note the added $ in var names, you can actually pass an array here will all objects you need

    $socket.on("find game", () => {
        $this.gameSearch = "finding"
    });
    ...
    ...
    ...
  }

socket.js

socket = io("http://localhost:8081")
socket.connect()
attachSockets(socket, this)

js , , .

+3
+2

All Articles