[英]include a file for Node.JS (vue)
所以我想知道如何包含另一個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"
})
...
我知道你提到你不需要導出,你想要內聯代碼,但我認為你不能輕易地實現這一點,但是如果你現在使用bable和es6作為vue js,你可以導出和導入。
但我保證你不會像你想的那樣復雜。 {而不是使它內聯將會有更多的開銷}(它只是我的觀點,你可能想要它有一個很好的理由:))
因為最后所有代碼都將在big
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里面一樣。
你不能完全按照你描述的方式去做,但我有另一個建議。 將所有socket.on
s放在一個單獨的文件中,例如
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文件加載到您的頁面,它應該給你你想要的..
您可能正在尋找export default
。 它將允許您導出函數或對象。
export default {
// anything
}
在此處查看更多示例: https : //developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.