【发布时间】: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