admin管理员组

文章数量:1287859

I'm passing a prop to a ponent 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>

I'm passing a prop to a ponent 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>
Share Improve this question edited Jun 17, 2022 at 22:25 Nikola Pavicevic 23.5k9 gold badges29 silver badges51 bronze badges asked Jun 17, 2022 at 14:32 Lx45Lx45 1551 gold badge3 silver badges12 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 10

try like following:

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

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>

I found this way

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

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

本文标签: javascriptUsing Watchers on props in vue3 Script SetupStack Overflow