我开始使用 Cloud Google 并在代码中实现了翻译 API,但我无法在回调之外使用响应。
methods:{
clicked(){
const text = "Olá";
const target = navigator.language;
googleTranslate.translate(text, target, function(err, translation){
console.log(translation.translatedText)
//this.newText = translation.translatedText;
});
//console.log(this.newText);
},
}
显示带有或不带有console.log 的错误。在 this.newText = Translation.translatedText;
渲染错误:“TypeError:无法读取未定义的属性‘newText’”
我想向用户展示模板中的答案。我该怎么做?
最佳答案
使用 function 关键字会更改“this”上下文。您可以将“this”保存在函数之外或使用箭头函数。
以下是如何使用箭头函数
methods:{
clicked(){
const text = "Olá";
const target = navigator.language;
googleTranslate.translate(text, target, (err, translation) => {
console.log(translation.translatedText)
//this.newText = translation.translatedText;
});
//console.log(this.newText);
},
}
关于javascript - 如何在方法之外使用google-translate-api翻译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60655712/