VueJS throws an error when trying to access the 'settings' property of an undefined object

I'm encountering an issue with my basic input in a Vue component. The input should update data on change, but instead I'm getting the error message

Uncaught TypeError: Cannot read property 'settings' of undefined

Vue component

<template>
    <div>
        <div class="inner_container">
          <p>
            URL:
            <span>{{settings.url}}</span>
          </p>
          <div class="input_row">
            <input
              class="input_text"
              id="getURL"
              type="url"
              inputmode="url"
              placeholder="Enter URL"
              title="URL"
              @input="changeUrl"
            />
            <label class="label_" for="getURL">URL Link</label>
          </div>
          <button class="button" @click="saveSettings">Save all Values</button>
        </div>
    <div>
</template>

<script>
import axios from "axios";
import _ from "lodash";

export default {
  name: "Home",
  data() {
    return {
      settings: {
        brightness: "",
      },
    };
  },
  methods: {
    changeUrl: _.debounce((e) => {
      this.settings.url = e.target.value;
    }, 500),
  },
};
</script>

I keep receiving the same error whenever there is an input change event.

Any insights on what might be causing this issue?

Answer №1

One issue you may encounter is that the arrow function's reference to this does not point to the desired object. One way to resolve this is by using a regular function and initializing the url property within the settings object:

new Vue({   
     el: '#app',
     data() {
          return {
               settings: {    
                    brightness: "",  
                    url: ""      
               },
          };
     },      
     methods: {     
          changeUrl: _.debounce(function(e) {    
               this.settings.url = e.target.value; 
          }, 500),
          saveSettings(){ 
          
          }           
     },        
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.19/lodash.min.js"></script>
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>

<div id="app">
     <div class="inner_container">
          <p>
               URL: <span>{{settings.url}}</span>
          </p>
          <div class="input_row">
               <input
                    class="input_text"
                    id="getURL"
                    type="url"
                    inputmode="url"
                    placeholder="Enter URL"
                    title="URL"
                    @input="changeUrl"
               />
               <label class="label_" for="getURL">URL Link</label>
          </div>
          <button class="button" @click="saveSettings">Save all Values</button>
     </div>
</div>

An alternative, more straightforward approach is to utilize v-model to assign the value to the variable:

new Vue({
     el: '#app',         
     data() {             
          return {                
               settings: {                  
                    brightness: "",                   
               },            
          };       
     },     
     methods: {      
          saveSettings(){               
          
          }       
     },  
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.19/lodash.min.js"></script>
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>

<div id="app">
     <div class="inner_container">
          <p>
               URL: <span>{{settings.url}}</span>
          </p>
          <div class="input_row">
               <input
                    class="input_text"
                    id="getURL"
                    type="url"
                    inputmode="url"
                    placeholder="Enter URL"
                    title="URL"
                    v-model="settings.url"
               />
               <label class="label_" for="getURL">URL Link</label>
          </div>
          <button class="button" @click="saveSettings">Save all Values</button>
     </div>
</div>

Answer №2

Hello there! Implementing debounce in your code can be done as shown below:

_.debounce(function(input) {
  this.data.url = input.target.value;
}, 500)

Answer №3

The issue lies in utilizing the keyword this within a function that is not invoked on a JavaScript class. Resolve this by substituting the this with a specific variable name, and assigning that variable name to a class.

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 the best way to retrieve a variable within an AngularJS controller?

I am working with a binding parameter eid: '@' Inside my constructor, you will find the following method: this.$onInit = () => { console.log('eid: ', this.eid) } console.log("eid in another section: ", this.eid) Upon running t ...

Oops, the element type specified is not valid. Make sure to use a string for built-in components when working with NextJs

I am incorporating SVG's as a component in my nextjs application, but I encounter the following error message: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. ...

PWA JavaScript struggling with GPS geolocation coordinates

I am experiencing issues with the GPS coordinates being stuck when using geolocation in a Progressive Web App (PWA). Sometimes, the coordinates get stuck at the previous location, even if the user has moved since then. I suspect that this is due to the GP ...

Creating a looping animation on multiple elements using jQuery that makes them fade in and out at different intervals

I am currently working on creating a fade in and out animation for multiple elements using jquery. It's a bit complex to explain, so I will start by sharing the relevant code. $(document).ready(function() { $("#1").delay(0).animate({ ...

unable to connect a value with the radio button

I am struggling to incorporate a radio group within a list of items. I am facing difficulty in setting the radio button as checked based on the value provided. Can anyone provide me with some guidance? Here is the HTML code snippet: <div *ngFor=" ...

Are HTML entities ineffective in innerHTML in javascript?

Take this example: <script type="text/javascript> function showText() { var text = document.getElementById("text-input").value; document.getElementById("display").innerHTML = text; } </script> <?php $text = "<html>some ...

Having issues with JavaScript and MySQL data retrieval following XMLHttp update to the database

After running the newNet.php file successfully creates a new entry and assigns it an auto-incremented netID. The next step is to retrieve this newly created ID and use it in the showActivities() function to display the record. Ideally, it should work like ...

Even after refreshing the page, Chrome stubbornly insists on showing the old data

I've been working on a single-page application where one page triggers server requests every time it loads. After making changes and deploying them, I noticed that the live version of the application was not reflecting the updates. Even though the cha ...

What is the best way to evaluate a sequence of actions and their outcomes?

Recently, I've dived into the world of writing automated tests for a React application. Along the way, I encountered some intriguing questions about the best approach to testing a series of interactions within the app. Let's imagine a scenario w ...

The $resource.query function will now return an array of characters instead of a single string when splitting strings

Recently, I've been working on utilizing an Angular $resource in my project. Here's a snippet of the code: angular.module('app') .factory('data', function ($resource) { var Con = $resource('/api/data', {}, { ...

Tracking changes in real time and calculating the sum with AJAX, PHP, and MySQL for efficient processing

Initially, I kindly request you to read this until the end. I am in dire need of assistance with my problem as I have searched for solutions but still remain clueless. https://i.sstatic.net/DAb1q.png Referring to the image provided, the first 'Produ ...

Ajax is incapable of achieving success or encountering failure

I'm having some trouble displaying search results on the view using AJAX. The action retrieves JSON data and sends it, but for some reason the AJAX call is not receiving the data. $(function () { $("#btnSearchForUser").click(function () { ...

What is the process for incorporating attribute values when constructing XML with fast-xml-parser?

Latest fast-xml-parser update: version 4.3.6 Description I'm trying to incorporate an xml attribute (tokenized="true") in this format : <custom-tag tokenized="true">test test &gt; 14</custom-tag> Input Code var def ...

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 ...

Ajax is displaying some unusual behavior

Currently, I am working on an ajax request to check if a specific combination of username or password exists. <script> $("form").submit(function(e){ e.preventDefault(); //send data to ajax file now $.ajax({ type: 'POST ...

Test results indicate successful completion of tests for VueJS component files, however code coverage does not reflect this for those

Currently, I am facing an issue while trying to obtain code coverage results for my VueJS frontend application. It seems that when I create a component and write a snapshot test for it, the file is being ignored by WebStorm. After some investigation, I di ...

Trouble with ng-repeat when working with nested json data

Check out this app demo: http://jsfiddle.net/TR4WC/2/ I feel like I might be overlooking something. I had to loop twice to access the 2nd array. <li ng-repeat="order in orders"> <span ng-repeat="sales in order.sales> {{sales.sales ...

Pedaling back and forth along a sequence

Is there a way to implement forward and backward buttons for a clickable list without using arrays, as the list will be expanding over time? I have already achieved changing color of the listed items to red, but need a solution to navigate through the list ...

What is the best way to trigger an event from a child component to a parent component in

parent.component.ts public test(){ //some code..... } parent.component.html <app-child (eventfire)="test($event)"></app-child> In this scenario, the child component button is displayed within the parent component. However, there i ...

Generate a JavaScript File/Blob from an image's URI

Can I generate a File or Blob object from an image URI? I am utilizing the Cordova Image Picker plugin in my mobile application to retrieve photo URIs like this: "file:///data/user/0/..../image.jpg" However, I am struggling to create a File or Blob objec ...