VueJS使用Yandex Translate API异步检测语言

时间:2019-05-07 20:40:27

标签: vue.js yandex-api

我正在尝试使用VueJS来测试Yandex Translate API,以异步检测输入文本的语言。

一切正常。但有个问题;我写的每个字母的日志返回。

例如,当我写“ hello”时:api会预测每个单词“ h”,“ he”,“ hel”,“ hell”,“ hello”的语言,并使其变为5 log。我想要的是,超时后API异步为单词“ hello”返回1个日志。它检查每个字母。我该如何解决?

TranslateForm.vue的HTML部分

<template>
    <textarea v-model="translateText" cols="30" rows="5" class="form-control" placeholder="Translate something."></textarea>
</template>

TranslateForm.vue的脚本部分

import axios from 'axios'
export default {
  name: 'TranslateForm',
  data () {
    return {
      translateText: '',
      apiKey: '********',
      detectLangApiUrl: '***********'
    }
  },
  watch: {
      translateText (value) {
        if (value) {
          axios.post(this.detectLangApiUrl + '?key=' + this.apiKey + '&text=' + value)
            .then(response => {
              console.log(response)
            }).catch(e => console.log(e))
        }
      }
   }
}

1 个答案:

答案 0 :(得分:1)

问题在于,每次translateText更新时(每次按键后),您都在调用API。如果您不想只拥有一个按钮,一种方法是监听 blur 事件(当用户将焦点移到文本区域之外时),然后调用该方法:

<template>
    <textarea v-model="translateText" @blur="translate" cols="30" rows="5" class="form-control" placeholder="Translate something."></textarea>
</template>

<script>
import axios from 'axios'
export default {
  name: 'TranslateForm',
  data () {
    return {
      translateText: '',
      apiKey: '********',
      detectLangApiUrl: '***********'
    }
  },
  methods: {
    translate () {
       if (this.translateText) {
          axios.post(this.detectLangApiUrl + '?key=' + this.apiKey + '&text=' + this.translateText)
            .then(response => {
              console.log(response)
            }).catch(e => console.log(e))
        }
    }
  }
}
</script>

您还可以使用debounce函数来限制该方法的调用次数。例如,每秒只调用一次翻译:

<script>
import axios from 'axios'
import { debounce } from 'lodash'

export default {
  name: 'TranslateForm',
  data () {
    return {
      translateText: '',
      apiKey: '********',
      detectLangApiUrl: '***********',
      debouncedTranslate: debounce(() => {
        axios.post(this.detectLangApiUrl + '?key=' + this.apiKey + '&text=' + this.translateText)
            .then(response => {
              console.log(response)
            }).catch(e => console.log(e))
      }, 1000)
    }
  },
  watch: {
      translateText (value) {
        if (value) {
          this.debouncedTranslate()
        }
      }
   }
}
</script>