0

How can I conditionally apply value to the data variable based on props, the ternary operator is generating error, I would like to refer to this code:

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

and I get the error saying :

TypeError
Cannot read property 'white' of undefined

I have tried to validate the props and set it to not required like so:

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

But it didn't help, what am I doing wrong? Thanks

1 Answer 1

3

If you need a data variable that depends of another variable, you must use a computed property.

You have to check about that on de official docs: Computed Properties

And instead of hamburguerUrl on data, you put it on the computed propert

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

And that's all.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.