Passing the default value of props to data in @Component

275 Views Asked by At

Having the code, I am getting State: undefined and clicking the toggle button does nothing. How to get the default value from @Prop to some data correctly using @Component?

<script lang="ts">
import {
  Component,
  Prop,
  Vue,
} from 'vue-property-decorator';

@Component
export default class HelloWorld extends Vue {
    @Prop({ type: Boolean, default: true })
    expanded!: boolean;
    
    isExpanded = this.expanded;
    // if its isExpanded = true; then toggling works.
}
</script>

<template>
  <div class="greetings">
    State: {{ isExpanded }}
    <br />
    <button @click="isExpanded = !isExpanded">Toggle</button>
  </div>
</template>
1

There are 1 best solutions below

1
Steven Spungin On

You should not mutate the prop. Instead send a message to the parent, and let the parent mutate it.

<button @click="$emit('update:expanded', !expanded)">Toggle</button>
<hello-world :expanded='theValue' @update:expanded='theValue=$event' />