vue中怎么使用protobuf

這篇文章主要介紹了vue中怎么使用protobuf,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

創(chuàng)新互聯(lián)公司主營舟曲網站建設的網絡公司,主營網站建設方案,app軟件定制開發(fā),舟曲h5微信平臺小程序開發(fā)搭建,舟曲網站營銷推廣歡迎舟曲等地區(qū)企業(yè)咨詢

為什么要使用Vue

Vue是一款友好的、多用途且高性能的JavaScript框架,使用vue可以創(chuàng)建可維護性和可測試性更強的代碼庫,Vue允許可以將一個網頁分割成可復用的組件,每個組件都包含屬于自己的HTML、CSS、JavaScript,以用來渲染網頁中相應的地方,所以越來越多的前端開發(fā)者使用vue。

官方解釋為:

Protocol buffers are a flexible, efficient, automated mechanism for serializing structured data – think XML, but smaller, faster, and simpler. You define how you want your data to be structured once, then you can use special generated source code to easily write and read your structured data to and from a variety of data streams and using a variety of languages. You can even update your data structure without breaking deployed programs that are compiled against the "old" format.

翻譯是(機翻---我英語不好)

協(xié)議緩沖區(qū)是用于序列化結構化數(shù)據(jù)的靈活,高效的自動化機制 - 思考XML,但更小,更快,更簡單。您可以定義一次數(shù)據(jù)的結構,然后您可以使用特殊的源代碼輕松地將結構化數(shù)據(jù)寫入各種數(shù)據(jù)流并使用各種語言讀取和讀取數(shù)據(jù)。您甚至可以更新您的數(shù)據(jù)結構,而不會中斷根據(jù)“舊”格式編譯的已部署程序。

特點:

  • 更簡單

  • 是3到10倍小

  • 速度要快20到100倍

  • 不太模糊

  • 生成更易于以編程方式使用的數(shù)據(jù)訪問類

代碼

在github上寫了個demo demo地址 有需要的可以下載下來跑一下就理解了。PS:如果覺得有用 請給我個小星星 (筆芯~)

使用

其實最開始我嘗試使用一個第三方JSprotobuf.js protobuf.load 的時候瀏覽器報了個錯illegal token '<' (/demo.proto, line 1) 查找了下官網issue,大意應該是proto文件多了個字符,但是我查看過proto文件并沒有發(fā)現(xiàn)有多的'<',怎么辦呢,最后放棄使用第三方。用官方提供的方法。

下載protobuf編譯器

下載地址 (我下載的是3.40版) github也提供了zip包,可自行下載 (目前最新版本是v3.6.0) 用來編譯proto為JS文件方便調用

配置環(huán)境變量

由于公司用的是win10 只需要將下載的文件地址添加到path即可 Mac與window命令唯一的區(qū)別就是需要將protoc改成protoc.exe 前提是需要添加環(huán)境變量

編寫proto文件

為了確保前后一致,下面是后臺寫給我的一個測試proto,我司后臺是java

syntax = "proto2";//protobuf版本
option java_package = "com.test.protobuf";
option java_outer_classname = "PersonMessage";
message Person {
 required int32 id = 1;
 optional string name = 2;
 optional string email = 3;
 repeated string list = 4;
 extensions 100 to 1000;//允許擴展的ID
}

message PersonTree {
 optional string id = 1;
 optional string title = 2;
 repeated PersonTree childs = 3;
}

extend Person {
 optional int32 count = 101;
 optional int32 likes_cnt= 102;
}

message PersonEx {
 optional int32 id = 1;
 extend Person {
  optional int32 px = 103;
  optional int32 py= 104;
 }
 optional Person p = 2;
}

使用vue-cli構建一個工程目錄

npm install -g vue-cli
vue init webpack my-project
cd my-project
npm install
npm run dev

安裝插件: npm install axios element-ui google-protobuf --save

編譯proto為JS

進入 awesome.proto 的存放路徑 使用如下命令 protoc.exe --js_out=import_style=commonjs,binary:. awesome.proto

  • 會生成一個awesome_pb.js文件

  • 點擊查看awesome_pb.js其實可以看到里面是生成好的方法。只需要在頁面中引入JS調用即可

之后我們將這個文件引入頁面,當然你也可以考慮全局引用

測試

本地測試

編寫一個測試頁面,創(chuàng)建一個測試按鈕 我是在測試頁面 import messages from './awesome_pb.js' 方法為:

methods: {
  protobufferTest () {
   var message = new messages.Person() // 調用Person對象 實例化
   // 賦值
   message.setId(23)
   message.setName('asd')
   // 序列化
   var bytes = message.serializeBinary()

   console.log(bytes) // Uint8Array(7) [8, 23, 18, 3, 97, 115, 100]

   // 反序列化
   var message2 = messages.Person.deserializeBinary(bytes)

   console.log(message2) // proto.PersonTree {wrappers_: null, messageId_: undefined, arrayIndexOffset_: -1, array: Array(3), pivot_: 1.7976931348623157e+308, …}

  }
 }

到此,本地測試完成,沒什么毛病了。

前后端聯(lián)調測試

前方有坑

前后傳輸是使用的FormData,然后悲劇的事情來了。后臺解析不了。查看了下數(shù)據(jù) [8, 23, 18, 3, 97, 115, 100] 確實是傳過去了。

后來排查出原因是應該是解析成了字符串,然后數(shù)值變了。所以解析不出來。 后來使用fromCharCode()方法編輯成字符串形式傳輸給后臺。在使用charCodeAt()取值。

此方法已棄用
protobufferTest () {
   var message = new messages.Person() // 調用Person對象 實例化
   // 賦值
   message.setId(23)
   message.setName('asd')
   // 序列化
   var bytes = message.serializeBinary()

   console.log(bytes) // Uint8Array(7) [8, 23, 18, 3, 97, 115, 100]

   var tests = ''
   for (let index = 0; index < bytes.length; index++) {
    tests += String.fromCharCode(bytes[index])
   }
   console.log(tests) // asd

   // 存入FormData
   let uploadDatas = new FormData()
   uploadDatas.append('protobuf', tests)

   // 使用axios傳輸給后臺
   this.axios.post('/test', uploadDatas)
    .then(function (response) {
     // 將傳回的字符串轉為數(shù)組
     console.log(response.data.split('')) // ["?", "", "3", "2", "", "", "a", "s", "d", "f"]
     let str = response.data.split('')
     let toChar = []
     for (let index = 0; index < str.length; index++) {
      toChar.push(str[index].charCodeAt())
     }
     console.log(toChar) // [10, 2, 51, 50, 18, 4, 97, 115, 100, 102]

     // 后臺傳回來的是PersonTree里面的值所以調用PersonTree來反序列化
     var message2 = messages.PersonTree.deserializeBinary(toChar)

     console.log(message2) // proto.PersonTree {wrappers_: null, messageId_: undefined, arrayIndexOffset_: -1, array: Array(3), pivot_: 1.7976931348623157e+308, …}

     // 獲取PersonTree的id值
     console.log(message2.getId()) // 32
    })
    .catch(function (error) {
     console.log(error)
    })

  }

以上方法可能存在安全隱患。 向后端傳值 因為FormData支持兩種方式傳輸string和blob所以將bytes存入blob中 前端獲取數(shù)據(jù) 對axios的默認傳輸方式做個更改 axios.defaults.responseType = 'arraybuffer' 將以上的JS代碼更改為以下內容

protobufferTest () {
   var message = new messages.Person()
   message.setId(23)
   message.setName('asd')
   var bytes = message.serializeBinary()
   
   console.log(bytes)
   let uploadDatas = new FormData()
   var blob = new Blob([bytes], {type: 'application/octet-stream'})

   uploadDatas.append('protobuf', blob)
   
   this.axios.post('/test', uploadDatas)
    .then(function (response) {
     console.log(response)

     var message2 = messages.PersonTree.deserializeBinary(response.data)
     console.log(message2.getId())
    })
    .catch(function (error) {
     console.log(error)
    })
   // console.log(bytes)
  }

至此前后聯(lián)調完成

感謝你能夠認真閱讀完這篇文章,希望小編分享的“vue中怎么使用protobuf”這篇文章對大家有幫助,同時也希望大家多多支持創(chuàng)新互聯(lián),關注創(chuàng)新互聯(lián)行業(yè)資訊頻道,更多相關知識等著你來學習!

網頁名稱:vue中怎么使用protobuf
分享路徑:http://muchs.cn/article16/gceidg.html

成都網站建設公司_創(chuàng)新互聯(lián),為您提供響應式網站網站導航、品牌網站建設、虛擬主機、網站制作品牌網站設計

廣告

聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)

成都網頁設計公司