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

What is causing it to give me 'undefined' as the result?

Trying to execute a script, test.al(); and within test.al, it calls getcrypt.php();. The php script is hosted on a webserver, and it is functioning properly. Here are the current scripts being used: JS var getcrypt = { php: function () { $.a ...

How to Utilize the Vue Instance With the 'this'

Trying to implement this in my VueJs methods results in an error message: this is undefined It seems like arrow functions may not be suitable as their this does not bind to the expected context. Switching to a regular function still causes the same err ...

if considering an integer value of 0 as equivalent to null

I am struggling with using axios to send data to an API in react. Despite the server successfully receiving the values, my code is not entering the if block as expected. Interestingly, when I make the same request from a rest client, it works perfectly. He ...

Issues with looping in Internet Explorer 8

Hey, I'm having an issue with this JavaScript function: function test(){ var count = 0; var date1 = $('#alternatestartdate').val(); var date2 = $('#alternateenddate').val(); ...

Modify the `value` of the `<input type=color>` element

Hello there! I have been working on a feature where I need users to select a color and have that choice reflected in the value field. Initially, I assumed this could be achieved easily through Bootstrap's features since my project is based on Bootstr ...

Aggregate the values in an array and organize them into an object based on their frequency

I have an array of information structured like this: 0: { first: "sea", second: "deniz", languageId: "English-Turkish"} 1: { first: "play", second: "oynamak", languageId: "English-Turkish&qu ...

Regular expression: Identify all instances of double quotes within a given string and insert a comma

Is there a way to transform a string similar to the following: ' query: "help me" distance: "25" count: "50" ' Into either a JavaScript object or a JSON string that resembles this: '{ query: "help me", distance: "25", count: "50" }' ...

javascript trigger not functioning

Currently, I am working with ASP development and incorporating jQuery into my projects. One challenge I've encountered is not being able to utilize the trigger function upon page load. Interestingly, my change function seems to work smoothly, except ...

ESLint consistently raising key-spacing error consistently

Within my .eslintrc file, I have the following code: 'key-spacing': [ 'error', { 'singleLine': { 'beforeColon' : false, 'afterColon' : true }, &apos ...

Navigating through external JSON data in a Node.js and Express application, and rendering the data using Jade

After going through various examples and solutions in related questions on StackExchange in an attempt to solve my issue, I have decided to post my question. My ultimate goal is to access complex JSON data via an API and REST. I intend to import this data ...

Issue with inconsistent functionality of Socket.io

I've encountered an issue while working with multiple modules - specifically, socket.io is not functioning consistently... We have successfully implemented several 'routes' in Socket.io that work flawlessly every time! However, we are now ...

Breaking Down the Process of Exporting a Next.js Static Website into Manageable Parts

I am facing memory issues while building my website using Next.js's Static HTML Export. The site has a large number of static pages, approximately 10 million. Is it feasible to export these pages in batches, like exporting 100k pages in each build ite ...

Refresh the table dynamically in Django without the need to reload the entire page

Seeking assistance to update a small table with new data every 10 seconds on a Django website. The data is parsed into JSON and refreshed in the database, then displayed on the front-end. Looking for help with writing AJAX code to continuously refresh the ...

Prevent elements from displaying until Masonry has been properly set up

My goal is to merge Masonry elements with existing ones. Currently, the items appear before Masonry initializes then quickly adjust into position a moment later. I want them to remain hidden until they are in their proper place. This is the snippet (with ...

The module specifier "logrocket" could not be resolved, make sure to use either npm or

I'm currently having an issue with initializing LogRocket. I followed the steps from the official documentation: I successfully installed it using node: npm i --save logrocket However, when trying to initialize it on my page earlier with: < ...

Nextjs doesn't render the default JSX for a boolean state on the server side

I am working on a basic nextjs page to display a Post. Everything is functioning smoothly and nextjs is rendering the entire page server side for optimal SEO performance. However, I have decided to introduce an edit mode using a boolean state: const PostPa ...

Mastering preventBack() Functionality - A Foolproof Method to Eliminate a Div on Back

This unique code prevents the page from going back when using the back button: <script type = "text/javascript" > function stopGoingBack(){window.history.forward();} setTimeout("stopGoingBack()", 0); window.onunload=function(){null}; ...

Express-hbs: Dynamic Helper Function with Additional Features

I am currently utilizing express-hbs and Async Helpers in my project. However, I am facing an issue with passing options to the helper as async helpers do not seem to support this feature (or maybe I am unaware of how to do it correctly). In the code snipp ...

Mastering Light and Camera Selection in Three.js

Question, In the editor found at this link, you can click on a light or camera to select it. I am familiar with using raycaster.intersectObjects(objects) to select meshes, but how can I achieve the same result for lights and cameras which do not have mesh ...

"Chrome experiences issues with onmouseover functionality when navigating away from a page or posting content

I'm experiencing an issue with a page where I have onmouseover and onmouseout attributes set for pictures. When submitting, the onmouseover and onmouseout events cause the images to fail, resulting in the image source not found icon being displayed. ...