如何在Vue中使用protobuf
protobuf
是由google
推出的和语言无关和平台无关,可扩展的序列化数据结构协议,类似于XML,但是比XML更小、更快、更简单。protobuf
几乎支持当前的大部分语言,如JavaScript
【如何在Vue中使用protobuf】安装protobufjs
cnpm i -S protobufjs
注意:当前protobufjs的版本为:6.11.2在项目src目录下新建proto目录,把后端给的
test.proto
文件放进去![如何在Vue中使用protobuf](https://img.it610.com/image/info11/0a05d67ffda4472e93bbe43603776fa1.png)
文章图片
syntax = "proto3"; //第一行指定了正在使用proto3语法:如果你没有指定这个,编译器会使用proto2。这个指定语法行必须是文件的非空非注释的第一行 message Address{string province= 1; string city = 2; string county = 3; }
打开dos窗口,执行以下命令将proto文件转换成js文件。大概执行15秒,执行成功后会在src/proto文件夹中创建proto.js文件
npx pbjs -t json-module -w commonjs -o src/proto/proto.js src/proto/*.proto
注意:-w参数可以指定打包js的包装器,这里用的是commonjs 。.proto文件除了可以生成js文件,还可以生成json文件。通常打包成js模块比较好用,因为vue在生产环境中打包后只有html,css,js等文件。生成json文件的命令为:
npx pbjs -t json src/proto/*.proto > src/proto/proto.json
![如何在Vue中使用protobuf](https://img.it610.com/image/info11/0894d123b82b43c487ea90e8da0ee68e.png)
文章图片
![如何在Vue中使用protobuf](https://img.it610.com/image/info11/651bb4f16a3b4673a8f8f97db66e185c.jpg)
文章图片
引入proto.js:
import protoRoot from "@/proto/proto.js";
先打印看看protoRoot内容:
![如何在Vue中使用protobuf](https://img.it610.com/image/info11/0e6c77c2c0d74ab9938a9b148b29d241.png)
文章图片
![如何在Vue中使用protobuf](https://img.it610.com/image/info11/397b1fe11587437193da8b079ff6ba1e.png)
文章图片
基本使用:
![如何在Vue中使用protobuf](https://img.it610.com/image/info11/4b25388292924dda963811482d63f2fe.png)
文章图片
![如何在Vue中使用protobuf](https://img.it610.com/image/info11/788d22e518f64ea5a7f4e9b92278d23e.png)
文章图片
main
为以后方便使用,我们可将命令添加到package.json的script中:
"proto": "pbjs -t json-module -w commonjs -o src/proto/proto.jssrc/proto/*.proto"
以后更新
proto
文件后,只需要npm run proto
即可重新生成最新的proto.js
![如何在Vue中使用protobuf](https://img.it610.com/image/info11/14274f4eaca248518646e192e467d387.png)
文章图片
使用axios发起请求时,需要注意设置axios的请求类型使用arraybuffer:
import axios from 'axios'const httpService = axios.create({timeout: 45000,method: 'post',headers: {'X-Requested-With': 'XMLHttpRequest','Content-Type': 'application/octet-stream'},responseType: 'arraybuffer'})
到此这篇关于如何在Vue中使用protobuf的文章就介绍到这了,更多相关Vue使用protobuf内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
推荐阅读
- 教你如何在Pycharm中导入requests模块
- vue左右滑动选择日期组件封装的方法
- Linux技术|如何创建 Azure AKS 集群()
- vue3使用vuedraggable实现拖拽功能
- 使用vuedraggable实现从左向右拖拽功能
- js如何操作localstorage
- vue拖拽组件vuedraggable使用说明详解
- vuedraggable实现拖拽功能
- 聚水潭ERP系统如何集成企微群机器人快速解决电商售后难题()
- 如何在|如何在 Java 中实现无向环和有向环的检测