包含Node.JS(vue)的文件

时间:2017-12-14 06:19:51

标签: javascript node.js vue.js vuejs2

所以我想知道如何按原样包含另一个JavaScript文件。就像PHP的include函数/关键字一样。我不是在寻找export函数,因为它只允许您使用其他文件中的变量。

我正在使用vue init webpack my-project

这是我基本拥有的(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"
    })
    ...
}

所以基本上我有一堆socket.on,我想进入另一个文件。我想知道如何将包含在中,以便它们能够像在那里插入代码一样工作(就像PHP include

最终可能会是什么样子:

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"
})
...

3 个答案:

答案 0 :(得分:5)

我知道你提到你不需要出口,你想要内联代码,但我认为你不能轻易地实现这一点,但如果你正在使用bable和es6作为vue js是现在,您可以导出和导入。

但我保证你不会像你想的那样复杂。 {而不是让它内联将会有更多的开销}(它只是我的观点,你可能想要它有一些很好的理由:))

  

因为最后所有代码都在大bundle.js

之内

可能它可以很简单,你只需将所有的coed包装到一个大函数中将它与主实例绑定,现在整个代码块看起来就像它在你的主文件里面但仍然在另一个文件中。

我假设你需要在es6,bable和import

中使用它

例如:假设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
  

现在我的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里面一样。

答案 1 :(得分:3)

你不能完全按照你描述的方式去做,但我有另一个建议。 将所有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文件加载到您的页面,它应该为您提供所需的内容..

答案 2 :(得分:2)

您可能正在寻找export default。它将允许您导出函数或对象。

export default {
    // anything
}

点击此处查看更多示例:https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export