"Error: Vue prop is not defined when passed to computed functions during initial call

I am encountering an issue with my Vue component. Here is the code for reference:

Vue.component('result', {
  props: ['stuff'],
  data: () => ({}),
  template: "<img :src='tag' class='result'></img>",
  computed: {
    tag: function() {
      return `pages/search/img/${this.stuff.type.toLowerCase()}_tag.png`;
    }
  }
});

Upon creating the component, I receive an error message:

TypeError: Cannot read property 'toLowerCase' of undefined
  at VueComponent.tag

Strange enough, without using toLowerCase(), the method functions correctly and generates the expected string. I could potentially adjust my file names to avoid this issue, but I am more interested in understanding why Vue is behaving like this. Why does a property become undefined only when methods are invoked on it?

Update: Further investigation revealed that this.stuff.type is indeed undefined during the initial computation of tag(). The usage of toLowerCase() simply exposes an error in what would have otherwise been a silent bug. Is there a specific reason why props are not defined when accessed from within a computed function for the first time? Should I be structuring my component differently?

Answer №1

At the time of creating the result component, the stuff prop is found to be undefined.

To resolve this issue, there are two possible solutions:

One option is to include the v-if directive in the parent component's template to ensure that stuff has a value when the result component is initialized:

<template>
  <result v-if="stuff" :stuff="stuff" />
</template>

Alternatively, you can handle the scenario where the stuff prop is undefined within the result component itself.

Vue.component('result', {
  props: {
    // Object with a default value
    stuff: {
      type: Object,
      // Object or array defaults must be returned from
      // a factory function
      default: () => ({ type: 'someType'})
    },
  },

  data: () => ({}),

  template: "<img :src='tag' class='result' >",

  computed: {
    tag: function tag() {
      return `pages/search/img/${this.stuff.type.toLowerCase()}_tag.png`;
    }
  }
})

Please note: The img element is a void element and does not require an end tag.

Answer №2

By default, props are set to null, but you can assign them a default value to resolve this issue.

For instance:

Vue.component('result', {
  props: {
    item: {
      type: Object,
      default: {
        category: ''
      }
    }
  },
  data: () => ({}),
  template: "<img :src='link' class='image'></img>",
  computed: {
    link: function() {
      return `images/${this.item.category.toLowerCase()}_img.png`;
    }
  }
});

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

In the ajax call, an empty JSON array object is sent as the data

Utilizing JSON data as a parameter for an ajax call: var startDate = dateFormatForSave($("#start_date").val().trim()); var arrayOfStudentsInfo = []; var table = $("#selected_students"); table.find('tr').each(function(i, el) { var rowId = $( ...

Attempting to minimize the number of jQuery calls within a Domino XPage

Trying to incorporate the 'DataTables' table plug-in for jQuery into a basic Domino XPage. Successfully loaded required libraries from CDN sources... JQuery: ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js DataTables: cdn.datatables. ...

Increasing space at the top with heading

As I scroll down, the header on my website remains in a static position and disappears. However, when I scroll back up, the header reappears wherever the user is on the page. While this functionality works well, I have noticed that as I scroll all the way ...

Problem with a for loop: retrieve only the final item

Using the fileReader to read the content of selected files and appending it to the DOM creates a paragraph element for each file. However, when attempting to store each file's content in local storage, only the last item is being saved. What could be ...

JS and its dynamic color changes

A game has been developed using JavaScript and HTML. The game features a table with cells that are assigned IDs for toggling colors using an onClick function. The objective is simple: when a cell is clicked, all neighboring cells, including the clicked one ...

Distinctive titles for JavaScript constructors/prototypes compared to classes

When working with JavaScript ES6, classes allow us to write code like this: class RectangularShape { constructor(height, width) { this.height = height; this.width = width; } getArea() { return this.height * this.width } static some ...

What is the best way to transform an array of objects into MenuItems for a Material-UI Select component?

I am facing an issue with mapping the values of field choices to create options for an MUI Select field from an array called fieldChoices. Here is how I populate the fieldChoices array: fieldChoices = { choices: filtered_status.map(function (item) { ...

Encountering a Vue syntax error following the binding of a session variable

Encountering a syntax error while attempting to bind a session variable as a prop of my Vue component. Scrutinizing my code did not reveal any mistakes, but perhaps another set of eyes may catch something. This is where I have registered my components: V ...

Angular Bootstrap notifications will stay open indefinitely and will not automatically dismiss after a certain period

I need help with adding alerts using Angular Bootstrap that should dismiss themselves after a certain timeout. However, the alerts are not dismissing on their own. Here's the code snippet: angular.module('ui.services').service('AlertSe ...

I am looking to transmit information to the controller using AJAX

ajax console.log(total);//10 console.log(number);//4 var form = { total:total, number:number } $.ajax({ url: 'items/cart/update', type: 'POST', data:form }); Spring MVC controller @ResponseBody @P ...

Does creating a form render the "action" attribute insignificant in an AJAX environment?

When submitting forms exclusively through AJAX, is there any advantage to setting the action attribute at all? I have yet to come across any AJAX-form guides suggesting that it can be left out, but I fail to see the purpose of including it, so I wanted t ...

The backend API seems to be facing issues with loading images fully in Vuejs

Scenario: In my WebApp (frontend: Vue3, backend: node.js + express), there is a single vue component with a button. Clicking this button triggers a script in the backend to download an image and save it locally. The goal is to render this image on the Vue ...

hitting the value of the text input

Is there a way to strike through only the first word in an input box of type text, without editing the html? I've tried using css text-decoration: line-through; but it's striking both words. Any suggestions on how to achieve this using javascript ...

Navigating from an error page to the homepage with Next.JS 13: A quick and easy guide

I'm currently working on implementing a feature that allows users to easily go back to the main page from an error page within the app folder. Specifically, in my weather app project, if a user enters an incorrect city, they should have the option to ...

Learn the process of utilizing JavaScript/Node.js to dynamically upload images onto a webpage directly from a database

Currently, I am developing a web application and building a user profile page where I aim to showcase user information along with a profile picture. Working with node/express/jade stack, I have a javascript file that manages loading the appropriate jade vi ...

Verify if spacebar is pressed and then use jQuery to add a hashtag with multi-language support

I am attempting to use jQuery to add a hashtag (#) after the user types and presses space. I have created a demonstration on CodePen. In this demo, when you type something like (how are you), the JavaScript code will change it to (#how #are #you). To ach ...

Change the class of each item in a list individually by hovering over them with the mouse using JavaScript

How to toggle classes in a list item one by one using the mouseover event in JavaScript? const items = document.querySelectorAll("ul li"); let currentItem; for (const item of items) { item.addEventListener("mouseover", e => { currentItem &am ...

Creating a custom pipe that converts seconds to hours and minutes retrieved from an API can be achieved by implementing a transformation function

Can someone please provide guidance on creating a custom pipe in Angular 8 that converts seconds to hours and minutes? Thank you. <div class="col-2" *ngFor="let movie of moviesList"> <div class="movie"> {{ movie.attributes.title }} ...

The position of the jQuery VirtualKeyboard is not displaying correctly

I'm currently experiencing an issue with the placement of the keyboard while using the Mottie/Keyboard plugin. The images provided below illustrate my desired outcome and the current behavior: https://i.sstatic.net/GULve.png Despite my attempts, the ...

Troubleshooting Issues with Implementing JavaScript for HTML5 Canvas

I've encountered an issue with my code. After fixing a previous bug, I now have a new one where the rectangle is not being drawn on the canvas. Surprisingly, the console isn't showing any errors. Here's the snippet of code: 13. var can ...