Using “this” in Vuejs 2.0

2019-07-09 08:06发布

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条回答
Evening l夕情丶
2楼-- · 2019-07-09 08:30

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.

查看更多
登录 后发表回答