Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my component not reacting to the changes? Vue3

I have a child component that takes in some props to decide for a state:

  export interface IProps {
    selected?: boolean,
    answered?: boolean
  }
  const {selected, answered} = defineProps<IProps>()

Depending on answered / selected different styles need to be applied. I tried this using computed function:

//  in template
  <div :class="cardClasses" />

// in setup script
  const classes = {
    base: "w-40 h-20 m-0 rounded-xl drop-shadow-lg flex justify-center items-center text-white text-shadow",
    default: "bg-primary hover:bg-primary/70 hover:ring-2 hover:ring-primary hover:ring-inset cursor-pointer",
    selected: "bg-primary/70 ring-teal-900 ring-2 ring-inset cursor-pointer",
    done: "bg-primary/40"
  }

  const status = computed(() => {
    if(answered) return "done"
    if(selected) return "selected"
    return "default"
  })
  const cardClasses = computed(() => `${classes.base} ${classes[status.value]}`)

The initial value for status is always ‘default’ but after clicking the child component it should turn to ‘selected’.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The state is hold by the parent component but I checked the value change for selected in the onUpdated:

  onUpdated(() => {
    console.log("updated")
    console.log(selected, status)
  })

selected changed to true but status is still on ‘default’.

How to I make this reactive?

>Solution :

Destructing the props makes them loose the reactivity, you should wrap them by toRefs then destruct them :

import {toRefs} from 'vue'

 export interface IProps {
    selected?: boolean,
    answered?: boolean
  }
  const props=defineProps<IProps>()

  const {selected, answered} = toRefs(props)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading