Vue中使用protobuf

json在线编辑器:https://www.89tool.com/ 

json转protobuf:https://www.89tool.com/json/json2protobuf

protobuf是由google推出的和语言无关和平台无关,可扩展的序列化数据结构协议,类似于XML,但是比XML更小、更快、更简单。protobuf几乎支持当前的大部分语言,如JavaScript 

安装protobufjs

cnpm i -S protobufjs

注意:当前protobufjs的版本为:6.11.2 

 在项目src目录下新建proto目录,把后端给的test.proto文件放进去

syntax = "proto3";//第一行指定了正在使用proto3语法:如果你没有指定这个,编译器会使用proto2。这个指定语法行必须是文件的非空非注释的第一行

message User {
  required string username = 0;
  required double password = 1;
  required bool isMan = 2;

  message OTHER {
    required double score = 0;
    required string address = 1;
  }

  required OTHER other = 3;

  message FRIENDS {
    required string name = 0;
    required double age = 1;
  }

  repeated FRIENDS friends = 4;
}

打开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

/*eslint-disable block-scoped-var, id-length, no-control-regex, no-magic-numbers, no-prototype-builtins, no-redeclare, no-shadow, no-var, sort-vars*/
"use strict";

var $protobuf = require("protobufjs/light");

var $root = ($protobuf.roots["default"] || ($protobuf.roots["default"] = new $protobuf.Root()))
.addJSON({
  User: {
    fields: {
      username: {
        rule: "required",
        type: "string",
        id: 0
      },
      password: {
        rule: "required",
        type: "double",
        id: 1
      },
      isMan: {
        rule: "required",
        type: "bool",
        id: 2
      },
      other: {
        rule: "required",
        type: "OTHER",
        id: 3
      },
      friends: {
        rule: "repeated",
        type: "FRIENDS",
        id: 4
      }
    },
    nested: {
      OTHER: {
        fields: {
          score: {
            rule: "required",
            type: "double",
            id: 0
          },
          address: {
            rule: "required",
            type: "string",
            id: 1
          }
        }
      },
      FRIENDS: {
        fields: {
          name: {
            rule: "required",
            type: "string",
            id: 0
          },
          age: {
            rule: "required",
            type: "double",
            id: 1
          }
        }
      }
    }
  }
});

module.exports = $root;

 引入proto.js:

import protoRoot from "@/proto/proto.js";

先打印看看protoRoot内容:

 

基本使用:

<template>
  <div class="main"></div>
</template>
<script>
import protoRoot from "@/proto/proto.js";
export default {
  mounted() {
    let testobj = protoRoot.lookup("User").create({
      username: "lijiang",
      isMan: true,
      other: {
        score: 90.23,
        address: "四川",
      },
      friends: [
        {
          name: "张三",
          age: 23,
        },
        {
          name: "lisi",
          age: 22.5,
        },
      ],
    });
    testobj.password = 123; //还可以以这种方式赋值
    console.log("testobj:", testobj);
    let testObjBuffer = protoRoot.lookup("User").encode(testobj).finish(); //encode数据
    console.log("testObjBuffer:", testObjBuffer);
    let testdata = protoRoot.lookup("User").decode(testObjBuffer); //decode数据
    console.log("testdata:", testdata);
  },
};
</script>

 为以后方便使用,我们可将命令添加到package.json的script中:

"proto": "pbjs -t json-module -w commonjs -o src/proto/proto.js  src/proto/*.proto"

以后更新proto文件后,只需要npm run proto即可重新生成最新的proto.js

注意:使用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'
})

可能出现的报错:

在使用‘json转protobuf在线编辑器‘时,需要注意转出来的protobuf要手动加上每行末尾的分号,如下:

此外,生成proto.js后,一定要记得检查各个字段是否一致,尤其是大小写,下划线这些! 

猜你喜欢

转载自blog.csdn.net/qq_40323256/article/details/123809155
今日推荐