javascript - 如何在方法之外使用google-translate-api翻译?

标签 javascript vue.js google-translation-api

我开始使用 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/

相关文章:

javascript - 在 Node.js 中编写格式化的 JSON

java - 在 JAVA 中解码谷歌翻译 API 响应

javascript - 如何在浏览器中获取 Google Cloud Translation API 的身份验证 token (chrome 扩展)

javascript - 检查对象内哪个数组的长度最大

javascript - 如何创建在 document.write 中存活的 JS 事件监听器?

javascript - 如何访问从 Blob 创建的 ArrayBuffer 的索引?

html - 列数未知/宽度相同的 CSS 网格布局

javascript - vuejs方法中的Parseint

vue.js - 根据当前路由动态显示组件,vuejs

javascript - 我应该在 google translate api 请求正文中放入什么参数?