Home > Back-end >  Using Watchers on props in vue3 Script Setup
Using Watchers on props in vue3 Script Setup

Time:06-18

Im passing a prop to a component declaring in which state it is. I want to watch the prop and set the css accordingly. But it does not work, can someone telling me what I'm doing wrong?

<script setup>
  import { onMounted, reactive, ref, watch, watchEffect } from 'vue'

  const props = defineProps({
    title: String,
    date: String,
    state: String,
  })

  let cardStatus = ref('')

  watch(props.state, () => {
    if (props.state === 'finished'){
      cardStatus.value = 'border border-success'
    }
  })
</script>

<template>
  <div :></div>
</template>

CodePudding user response:

try like following:

watch(
  () => props.state,
  (newValue, oldValue) => {
    if (newValue === 'finished') cardStatus.value = 'border border-success'
  }
);

CodePudding user response:

I found a way to make it work.

<script setup>
  import { onMounted, reactive, ref, watch, watchEffect } from 'vue'

  const props = defineProps({
    title: String,
    date: String,
    state: String,
  })

  let cardStatusClass = ref('')
  
  watchEffect(() => {
    if (props.state === 'finished'){
      cardStatusClass.value = 'border border-success'
    }
  })
</script>
  • Related