【问题标题】:How to store chrome identity api response in vuejs component如何在 vuejs 组件中存储 chrome 身份 api 响应
【发布时间】:2020-05-09 15:09:34
【问题描述】:

我正在将来自 chrome 身份 api 的响应传递到将运行我的 vue 驱动的 chrome 扩展的选项卡。我需要将此信息存储在我的 vue 实例中,然后在组件中使用它。我尝试使用this.username 将信息分配给变量,但它会导致控制台中未定义。代码有什么问题,最好的方法是什么?

组件代码

<script>
import { EventBus } from '../../event-bus';

export default {
  data () {
    return {
      socket: null,
      isRegistered: false,
      isConnected: false,
      username: null,
      message: '',
    }
  },
  created() {

  },
  mounted() {
    chrome.runtime.onMessage.addListener(
      function(request, sender){
      console.log(request);
      this.username = request.name;
      this.isRegistered = true;
    });
    EventBus.$emit('open-connection')
// the variable is undefined and also the open-connection event are not emitted?
    console.log(this.username)
    EventBus.$on('connected', (socket) => {
      console.log(socket)
      this.socket = socket;
      this.isConnected = true;
      console.log(this.socket.id)
    })
  },
  methods: {
// I was using this method but the function isn't called inside mounted, result in an error :(
    connect(){
      //if( this.isRegistered === false){
        //this.username = this.username;
        //this.isRegistered = true;
        //EventBus.$emit('open-connection')
        //return this.username;
     // }
    }
    // methods here 
  }
}
</script>

<style scoped>

</style>

来自身份 api 的响应(出于隐私考虑,我将省略字段值):

{
  "id": "100xxxxxx",
  "name": "xxx",
  "given_name": "xxxx",
  "family_name": "xxxx",
  "picture": "https://lh4.googleusercontent.com/xxxxx.jpg",
  "locale": "xx"
}

注意:通过这种方式无法访问响应对象key.val

编辑

经过一些调试,我终于找到了解决方案。 api 检索到的响应信息并不是真正的对象,而是 JSON。我已经使用JSON.parse() 函数将其设为对象,现在我可以使用key.value 语法访问字段。

【问题讨论】:

    标签: javascript vue.js google-chrome-extension


    【解决方案1】:

    也许您可以使用chrome.storage 来设置/获取数据,而不是依赖组件状态。

    要不然你能分享一下console.log(request)给你的是什么以及后台脚本是什么样子的吗?

    【讨论】:

    • 如果我登录,我可以看到一个对象,但我无法在 vue 中使用它的属性,例如 request.name
    • 你能分享你得到的对象吗?
    • 我想我看到了一个问题。 addEventListener 使用回调来设置用户名。如果您在分配后立即控制台记录this.username,则可以看到这一点。您可以尝试在回调 (function(request, sender) 中移动您的 eventBus 逻辑,这样您就知道在调用 EventBus.$emit 时设置了用户名。
    • 我已经修改了代码以尝试寻找解决方案,但似乎无法以任何方式访问来自身份 api 的响应对象。我正在尝试在扩展的后台脚本中记录单个字段,但这会导致控制台中的undefined
    猜你喜欢
    • 2019-09-05
    • 2019-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-05
    • 1970-01-01
    • 2021-01-23
    • 2020-08-24
    相关资源
    最近更新 更多