【问题标题】:how to use the google-translate-api translation outside the method?如何在方法外使用 google-translate-api 翻译?
【发布时间】:2020-03-12 14:01:34
【问题描述】:

我开始使用 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: Cannot read property 'newText' of undefined”

我想在模板中向用户显示答案。我该怎么做?

【问题讨论】:

    标签: javascript vue.js google-translation-api


    【解决方案1】:

    使用 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);
        },
    }
    

    【讨论】:

    • 非常感谢。你能更好地解释函数和 => 之间的区别吗?我不明白什么时候需要使用其中一个
    • 箭头函数被认为更容易编写,因为您不必编写 'function' 或 'return',但它们是 ES6 功能,这意味着如果您需要转译代码'目标是 IE11。大多数情况下,您可以毫无问题地使用箭头函数。我发现this article 擅长解释它们。
    猜你喜欢
    • 2014-04-21
    • 2015-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-18
    • 1970-01-01
    • 2020-02-11
    相关资源
    最近更新 更多