vue.js项目中protobuf协议的处理流程
在前端开发中,关于protobuf协议的处理非常少,而后端开发中却非常常见。今天刚X中遇到前端也要处理protobuf。记下心得。
- 引入库文件
npm install -g protobufjs2.准备hello.proto文件
syntax = “proto3”;
package grpc;
message HelloMessage {
uint32 id = 1;
string name = 2;
string msg = 3;
}
3.生成hello.js文件
pbjs -t static-module -w es6 -o hello.js hello.proto4 引入hello.js
import {grpc} from “@/util/protobuffer/hello.js”
5 代码示例
import {grpc} from “@/util/protobuffer/hello.js”export default {
components: {
},
data(){
return {
messageBuf:”,
}
},
created() {
console.log(‘created’)
this.encode2Protobuf()
let that = this
setTimeout(functiоn(){
that.decodeFromProtobuf(that.messageBuf)
},2000)
},
methods:{
encode2Protobuf(){
let message = new grpc.HelloMessage()
message.id = 1
message.name = “mayun”
message.msg = “hello world”
let buf = grpc.HelloMessage.encode(message).finish()
this.messageBuf = buf
console.log(buf)
},
decodeFromProtobuf(buf){
let message = grpc.HelloMessage.decode(buf)
console.log(message.name)
console.log(message.msg)
}
}
}
完成!
原创文章,作者:starterknow,如若转载,请注明出处:https://www.starterknow.com/126792.html