using VueJS, learn how to dynamically apply text to a data variable based on certain props

I'm facing an issue with conditional value assignment to the data variable based on props. The ternary operator is causing errors in my code. Here's a snippet for reference:

<template>
  <div class="absolute left-3 top-1/2">
    <img
      :src="hamburgerUrl"
      style="width: 25px; cursor: pointer; transform: translateY(-50%)"
      alt="toggle menu button"
    />
  </div>
</template>

<script>
export default {
  name: "HamburgerMenu",
  props: ["white"],
  data: {
    hamburgerUrl: this.white
      ? "/gfx/hamburger-white.png"
      : "/gfx/hamburger-menu.png",
  },
};
</script>

When testing this code, I encounter the error message :

TypeError
Cannot read property 'white' of undefined

I attempted to make the prop not required and set a default value like so:

  props: {
    white: {
      type: Boolean,
      required: false,
      default: false,
    },
  },

However, it doesn't seem to resolve the issue. Can anyone point out what might be wrong? Thank you

Answer №1

If you are in need of a data variable that is dependent on another variable, it is important to utilize a computed property.

For more information on this topic, please refer to the official documentation: Computed Properties

Instead of storing 'hamburguerUrl' in the data section, consider using a computed property for better management.

<script>
export default {
  name: "HamburgerMenu",
  props: ["white"],
  computed: {
    hamburgerUrl() {
      return this.white
        ? "/gfx/hamburger-white.png"
        : "/gfx/hamburger-menu.png";
    }
  },
};
</script>

That concludes everything.

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

The class instances are not invoking the decorators

I'm experiencing issues with my decorators. It seems that the decorators are not being invoked on every instance of the class. While I understand that decorators are called during declaration time, I am wondering if there is a way to call them for eac ...

Conceal descendant of list item and reveal upon clicking

In my responsive side menu, there is a submenu structured like this: .navbar ul li ul I would like the child menus to be hidden and only shown when the parent menu is clicked. Although I attempted to achieve this with the following code, it was unsucces ...

What is the best way to iterate through a puppeteer selector's response in a loop?

So, by using page.evaluate I can accomplish the following: await page.evaluate(function() { var links = document.querySelectorAll('a'); for (var i = 0; i < links.length; i++) console.log(links[i].href); }); However, I am interested in a ...

Issues with v-model functionality on input field in Laravel app when using Vue JS are causing problems

Currently, I am integrating vuejs into a Laravel app for some minor functionality. For some unknown reason, v-model is not functioning as expected. Below is the base layout blade file created using php artisan make:auth, with most of the content removed: ...

why is the sum coming out as an undefined number?

My challenge involves creating a table that should display the total price, however, it keeps showing NaN. The code snippet below outlines how the total price is calculated: import React from 'react'; const Total = (props) => { const {ite ...

JavaScript code snippet for detecting key presses of 3 specific arrow keys on the document

For this specific action, I must press and hold the left arrow key first, followed by the right arrow key, and then the up arrow key. However, it seems that the up arrow key is not being triggered as expected. It appears that there may be some limitations ...

yet another scenario where the component's state changes without the component reflecting those changes

My react component includes a state variable called: showEditor When showEditor is set to false, the component should display a div containing a number (initially showEditor is false). If the state variable is true, the component should display a textbox ...

Executing npm run build index.html results in a blank page being generated without any error messages or warnings

After building my react app with npm run build, I encountered a problem where clicking on index.html resulted in a blank page opening in the web browser. I explored several solutions to address this issue but none seemed to work. Some of the strategies I ...

Troubleshooting Problem with Scrolling Sticky Element on iOS Devices

This is specifically for mobile devices I am facing an issue with a relative positioned element where it should become fixed to the top of the screen when the scroll position exceeds the top position of the element. However, in iOS, when scrolling, the f ...

Displaying Title and Description Dynamically on Markers in Angular Google Maps

I am currently utilizing Angular-google-maps, and here is the HTML code snippet: <ui-gmap-google-map center='mapData.map.center' zoom='mapData.map.zoom' events="mapEvents"> <ui-gmap-markers models="mapData.map.markers ...

Remove a comment from the page without needing to refresh the entire

Is there a way to enhance this code so that when a comment is deleted, the page does not refresh? It can be frustrating when deleting a comment causes the page to scroll back to the top. AJAX function deleteComment(pid){ $.ajax({ type: "PO ...

Vue: The best method to incrementally update properties within props

I am in the process of developing a component that will update props with values retrieved from local storage. These props consist of objects with multiple boolean properties, such as this.globalStates.repeat = false. As I have more than one prop to update ...

Combining Vue.js with Laravel Blade

I've encountered an issue while trying to implement a Basic Vue script within my Laravel blade template. The error message I am getting reads: app.js:32753 [Vue warn]: Property or method "message" is not defined on the instance but referenc ...

Is there a way to implement field validation in a Vue wizard form?

Trying to implement form validation using Joi in a Vue wizard form, but not sure how to set it up correctly. The objective is to control the fields before progressing to the next and final page using the next() method. I want to keep the simplicity of th ...

Vue Labyrinthine Design theme

Looking for some guidance from experienced developers out there! I'm currently exploring how to incorporate Mazeletter as a background feature for each page in an app project I've been working on. This is all new territory for me, so any assista ...

Filtering a subarray in Angular using ng-repeat

While working with Angular, I am attempting to filter data using ng-repeat based on the FactorName property in the given schema. Unfortunately, trying to use <... ng-model="query.Factors.FactorName" ...> as a filter does not produce the desired re ...

Linking the location of the pop-up to the currently selected text box

I am currently experimenting with setting the top and left values relative to the selected_element (which is active at the time of triggering the popup) in a manner similar to a tooltip. I attempted to use $().position() in combination with jQuery, but it ...

Transfer attributes, but have exclusions in React

At times, we all have a common practice of wrapping DOM elements in custom components. <CustomComponet id="abc" title="abc" nonDomProp="abc" ...andsoforth /> In this example, the custom component wraps a button with pr ...

Effortless method to handle package.json configurations

Is there a better approach for seamlessly transitioning between using npm link and git, or another solution that caters well to both front end and back end developers? The dilemma I'm facing revolves around developing a website that utilizes multiple ...

Exploring nuxtServerInit for Handling API Requests

I am currently utilizing nuxt.js along with Firebase as my API source. Utilizing the nuxtServerInit method, I am able to fetch all of my products from the Firebase API in one go. With just 3 categories and around 20 products, the API request remains relati ...