1

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

一切正常。但有个问题; 我写的每封信都会返回日志。

例如,当我写 'hello' 时:api 会预测每个单词 'h'、'he'、'hel'、'hell'、'hello' 的语言并变成 5 log。我想要的是 API 在超时后异步返回 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))
        }
      }
   }
}
4

1 回答 1

1

问题是每次更新 translateText 时(每次按键后)您都在调用 API。如果您不想简单地拥有一个按钮,那么一种方法是监听blur事件(当用户将注意力移出 textarea 时)然后调用该方法:

<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函数来限制调用该方法的次数。例如,每秒只调用一次 translate:

<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>
于 2019-05-07T20:52:11.647 回答