4

I'm 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 :class="'bg-main-light rounded-2xl w-full p-3 lg:px-5 ' + cardStatus"></div>
</template>

3 Answers 3

12

try like following:

watch(
  () => props.state,
  (newValue, oldValue) => {
    if (newValue === 'finished') cardStatus.value = 'border border-success'
  }
);
Sign up to request clarification or add additional context in comments.

5 Comments

It does not work like that, but I just found a way myself
@Lx45 It should work exactly the same way as in your post.
I agree - this is how to use watch on a prop, not sure why OP can't make it work, probably doing something wrong - probably because in the question he changes cardStatus.value and in his answer cardStatusCard.value
I agree with you, this answer is right. In my case I needed to use watchEffect because the watcher had to bet triggered initially.
I needed to add { immediate: true } in order to get this to work.
0

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>

Comments

0

I found this way

const retWatch: any = toRef(props, 'props.state');

watch([retWatch], (newValue) => {
    console.log(newValue);
    
});

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.