grpc在vue+typescript中集成丨技术开发分享录

grpc在vue+typescript中集成

{{ detail.nickname }}

转载 翻译 {{ formatTime(detail.create_time) }} 字数 {{ detail.content && detail.content.length }} 阅读 {{ detail.read_num }} {{ formatTag(v) }}

"看这篇之前,先看下前篇文章:http://fenxianglu.cn/article/285 ,因为这篇是在上篇的基础上实现的\n\n至于`.d.ts`和`.ts`文件的生成需要看这篇:http://fenxianglu.cn/article/244\n\n生成的ts文件如下:\n\nHelloWorld_pb.d.ts\nHelloWorld_pb_service.d.ts\n\n需要安装的依赖包,在创建vue项目的时候选好typescript就集成了\n\n完整`.vue`文件代码示例:\n\n```markup\n<template>\n  <div class=\"home\">\n    {{ computedMsg }}\n  </div>\n</template>\n\n<script lang=\"ts\">\nimport Vue from 'vue';\nimport Component from 'vue-class-component';\n\nimport * as GreeterGRPC from '@/assets/protos/HelloWorld_pb_service'; // 不需要加后缀.d.ts\nimport * as GreeterPb from '@/assets/protos/HelloWorld_pb'; // 不需要加后缀.d.ts\n\n@Component\nexport default class Home extends Vue {\n  msg = 'Hello world !';\n\n  get computedMsg () {\n    return this.msg\n  }\n\n  getMsg() {\n    let client = new GreeterGRPC.GreeterClient(process.env.VUE_APP_HOST); // 建议http连接\n\n    let helloRequest = new GreeterPb.HelloRequest();\n    helloRequest.setName('tom');\n    helloRequest.setCity('合肥');\n\n    let metaHeader: any = {}; // 哈哈,一起快乐的any吧\n    \n    client.sayHello(helloRequest, metaHeader, (err, response: any) => {\n      if(err) {\n        console.log(err);\n      } else {\n        let result = response.toObject();\n        this.msg = result.message;\n        console.log(result); // {message: \"hello tom and city is 合肥\"}\n      }\n    });\n  }\n\n  mounted () {\n    this.getMsg();\n  }\n}\n</script>\n```"
PS:写作不易,如要转裁,请标明转载出处。

如果此篇对您有帮助,可小额赞助,以兹鼓励!

猜你想看