Exploring the power of "this" in Vue.js 2.0

Seeking help with a VueJS issue. I am trying to create a voice search button that records my voice and prints it out in an input form.

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

Below is the script written 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>

Although I can fetch text from voice recognition, I'm facing difficulty displaying it in the input form.

Thank you!

Answer №1

To maintain the scope of `this` in JavaScript, consider using arrow syntax from ES6 instead of the traditional function keyword. Here's an example:

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

Another option is to store `this` in a separate variable and use that variable within the function like so:

var self = this
recognition.onresult = function(e) {
  self.inputSearch = e.results[0][0].transcript;
  recognition.stop();
};
recognition.onerror = function(e) {
      alert('Something went wrong...');
      recognition.stop();
};

You can refer to a similar answer I provided here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble enabling push notifications on Android with ngCordova

Having trouble with push notifications through the ngCordova plugin. Followed the sample code from (with a slight change - no deviceready listener, code inside ionicPlatform.ready listener) Below is the code snippet: angular.module('myApp', [& ...

Steps for integrating WebRTC recording functionality with a Node.js server

Looking to develop a user-friendly video blogging solution that utilizes WebRTC technology for direct recording of video/audio within the browser, similar to Youtube's My_Webcam. The backend should be powered by Node.js. While exploring various Node. ...

"Utilizing a function from an external file within the Main App function - a step-by-step guide

I am currently learning React.js and I have come across a challenge that I'm unable to solve easily. I am trying to use functions instead of classes in my code, but I am struggling with using these functions as components within my Main function. Here ...

Ensure that the extension is only loaded once Angular has fully loaded

I am currently working on a Chrome extension that incorporates event listeners to elements within a page utilizing Angular 1.2.10. The following code snippet is an example of what I have: window.addEventListener("load", (event) => { var switchButton = ...

What is the most effective way to retrieve IDs from Firestore and add them to the object arrays?

Currently working on a project that involves React and Firestore, I'm attempting to retrieve the Ids back into the objects array. Below is the code snippet: function grabIds() { setIsLoading(true); reference.onSnapshot((querySnapshot) => ...

Attempting to output numerical values using Jquery, however instead of integer values, I am met with [Object object]

I am struggling to figure out how to display the value contained in my object after attempting to create a Calendar using Jquery. I attempted to use JSON.toString() on my table data, but it didn't solve the issue. Perhaps I am not placing the toString ...

Utilizing PHP Variables in Ajax Calls: Transferring Data between JS and PHP

I've been struggling to grasp how to pass information from PHP to JavaScript and vice versa. I've spent an entire night trying to figure this out and would really appreciate it if someone could help me understand how to send two variables to an a ...

When using JavaScript to dynamically load canvases and create drawing contexts within a function, the context may suddenly disappear

Currently, I am modifying the canvases displayed through ajax calls and also updating what is drawn on each canvas. The primary issue I am facing is that my main drawing function fails on getContext and there are some unusual behaviors such as missing canv ...

How can I make Material UI's grid spacing function properly in React?

I've been utilizing Material UI's Grid for my layout design. While the columns and rows are functioning properly, I've encountered an issue with the spacing attribute not working as expected. To import Grid, I have used the following code: ...

Failure to Trigger Error Callback in Ajax Requests

I am encountering an issue with the error callback not being called when I pass the error function as an object parameter in a function. Strangely, when I define it directly within the ajax code, it works without any problems. var options = new Object(); ...

Showcasing pictures on ReactJS

I am currently working on developing an application to showcase images on my React webpage. These images have already been uploaded to a local folder. In order to integrate my React application with a NodeJS server and MongoDB, I connected the two. My goa ...

Using JavaScript to insert a value through AJAX

I'm currently working on a website that displays the value of a .TXT file, and here is the progress I've made so far: <script> $(document).ready(function() { $("#responsecontainer").load("info.txt"); var refreshId = setInterval(function( ...

Simulating a PubSub publish functionality

I have been trying to follow the instructions provided in this guide on mocking new Function() with Jest to mock PubSub, but unfortunately I am facing some issues. jest.mock('@google-cloud/pubsub', () => jest.fn()) ... const topic = jest.fn( ...

The bootstrap switch button remains in a neutral grey color

Ordinary: Initially clicked: Click again: After the second click, it remains grey and only reverts on a different action like mouse click or selection. Is there a way to make it go back to its original state when unselected? ...

Establishing flow types and generating unchangeable records

Looking to integrate Flow with Immutable.js Records, I've set up my record like this: const MyRecord = new Immutable.Record({id: undefined}) Now when I create records using new MyRecord({id: 1}), Flow gives me an error: constructor call Construct ...

What steps should I take to display a Material UI grid in React without triggering the warning about the missing unique key

In my current project, I am utilizing React and Material UI to display a grid. The grid's rows are populated from an array of data, with each row containing specific information in columns structured like this: <Grid container> {myData.map((re ...

Storing data locally and replacing the current URL with window.location.href

My course mate and I are working on writing a code that saves an order to local storage and redirects to an order page when the order button is clicked. However, we are facing issues where clicking on the order button doesn't register in the applicat ...

Attempting to determine income in JavaScript with the inclusion of two distinct rates

Trying to come up with a salary calculation for different rates within the same timeframe is proving to be quite challenging. For instance, between 10:00-15:00 the rate is $20 per hour and from 15:00 onwards it drops to $15 per hour. Check out the entire ...

What is the best way to reposition a column as a row when the user interface transitions to a different screen or

Welcome to my UI experience! https://i.stack.imgur.com/gOwAn.png Check out how the UI adapts when I resize the browser: https://i.stack.imgur.com/MyxpR.png I aim for the left component to be visible first, followed by scrolling to see the right compone ...

Exploring the functionality of localeRoute in vuex with the nuxt-i18n package

I'm attempting to utilize the localRoute method from nuxt-i18n this.$router.push(this.localeRoute({ name: "home" })) I gave this approach a shot, but it doesn't seem to be working. Can anyone suggest the correct way to accomplish this ...