Skip to content

Instantly share code, notes, and snippets.

@rusco
Last active February 11, 2022 23:00
Show Gist options
  • Save rusco/4bd61dd46dc9051490472334f3b05f4b to your computer and use it in GitHub Desktop.
Save rusco/4bd61dd46dc9051490472334f3b05f4b to your computer and use it in GitHub Desktop.
Vue.js usage with Golang Wasm
localhost:8080
gzip
log ../access.log
mime .wasm application/wasm
set GOOS=js
set GOARCH=wasm
go build -o app.wasm main.go
html, body {
margin: 5px;
padding: 0;
}
<html>
<head>
<link rel="stylesheet" href="index.css">
<script src="vue.js"></script>
</head>
<body>
<div id="app">
<input type="text" v-model="message" size="20"></input>
<button v-on:click="reverseMessage">Reverse Message</button>
<button v-on:click="log">Log</button>
<div>
<pre>{{$data}}</pre>
</div>
</div>
<script src="wasm_exec.js "></script>
<script>
if (!WebAssembly.instantiateStreaming) { // polyfill
WebAssembly.instantiateStreaming = async (resp, importObject) => {
const source = await (await resp).arrayBuffer();
return await WebAssembly.instantiate(source, importObject);
};
}
const go = new Go();
let mod, inst;
WebAssembly.instantiateStreaming(fetch("app.wasm"), go.importObject).then((result) => {
mod = result.module;
inst = result.instance;
go.run(inst);
WebAssembly.instantiate(mod, go.importObject); // reset instance
});
</script>
</body>
</html>
// +build js,wasm
package main
import (
"syscall/js"
)
const (
msg = "Welcome Wue.go"
el = "#app"
)
//M type
type M = map[string]interface{}
//Log function
func Log(i ...interface{}) {
js.Global().Get("console").Call("log", i...)
}
func reverse(s string) (result string) {
for _, v := range s {
result = string(v) + result
}
return
}
func main() {
Vue := js.Global().Get("Vue")
app := M{
"el": el,
"data": M{"message": msg},
"methods": M{"reverseMessage": js.NewEventCallback(js.PreventDefault, func(ev js.Value) {
data := js.Global().Get("app").Get("$data")
mess := reverse(data.Get("message").String())
data.Set("message", mess)
}),
"log": js.NewCallback(func(args []js.Value) {
Log(js.Global().Get("app").Get("$data"))
})},
}
js.Global().Set("app", Vue.New(app))
select {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment