我是VueJS的新手。 我有一个小问题,我无法弄清楚。希望有人可以给我一个提示。
我正在创建一个语音搜索按钮,基本上当我点击语音按钮然后它会录制我的声音并将其打印到表单中的输入属性。
<input type="text" name="inputSearch" id="inputSearch"
v-model="inputSearch" class="form-control" x-webkit-speech>
这是我在VueJS中的脚本
<script>
export default {
data() {
return {
inputSearch: '',
show: false
}
},
methods: {
voiceSearch: function(event){
this.inputSearch = '';
this.show = false;
if (window.hasOwnProperty('webkitSpeechRecognition')) {
var recognition = new webkitSpeechRecognition();
recognition.continuous = false;
recognition.interimResults = false;
recognition.lang = "en-US";
recognition.start();
recognition.onresult = function(e) {
this.inputSearch = e.results[0][0].transcript;
recognition.stop();
};
recognition.onerror = function(e) {
alert('There are something wrong...');
recognition.stop();
};
}else {
alert('Your browser does not support HTML5/WebKitSpeech. You are not able to use this functionality');
}
}
}
}
</script>
我可以从语音识别中获取文本,但无法在输入表单中显示。
谢谢,
答案 0 :(得分:4)
而不是使用function
使用ES6的箭头语法,这保持了完整的范围,如下所示:
recognition.onresult = (e) => {
this.inputSearch = e.results[0][0].transcript;
recognition.stop();
};
recognition.onerror = function(e) {
alert('There are something wrong...');
recognition.stop();
};
或其他选项是将this
保存在其他变量中并使用该变量,如下所示:
var that = this
recognition.onresult = function(e) {
that.inputSearch = e.results[0][0].transcript;
recognition.stop();
};
recognition.onerror = function(e) {
alert('There are something wrong...');
recognition.stop();
};
您可以查看我的类似答案here。