Using “this” in Vuejs 2.0

时光总嘲笑我的痴心妄想 提交于 2019-12-11 03:10:07

问题


I am new in VueJS. I am having a small problem that i could not figure it out. Hope some one can give me a hint.

I am creating a voice search button, basically when i click the voice button then it would record my voice and print it out to the input attribute in form.

<input type="text" name="inputSearch" id="inputSearch"
v-model="inputSearch" class="form-control" x-webkit-speech>

This is my script in 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>

I am able to get the text from the voice recoginization but can not show it in the input form.

Thanks,


回答1:


Instead of using function use arrow syntax of ES6, which keeps scope of this intact, like this:

                recognition.onresult = (e) => {
                   this.inputSearch = e.results[0][0].transcript;
                   recognition.stop();
                };
                recognition.onerror = function(e) {
                      alert('There are something wrong...');
                      recognition.stop();
                };

or other option is to save this in some other variable and use that variable like following:

                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();
                };

You can have a look at my similar answer here.



来源:https://stackoverflow.com/questions/41820258/using-this-in-vuejs-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!