Using watchEffect in Vue to detect props changes

Let's assume that you have the following component:

vue
<template>
    <div class = 'white'>{{ total }} messages</div>
</template>

<script>
export default {
    props: ['total']
}
</script>

The component receives the variable total as a prop and renders the total number of messages.

Now let's suppose that you want to change the class of the component depending on the props.

For example, let's assume that you want to display the block's background in red for 1 second after a props change.

Assign a variable to the class

The first step is to create a variable and bind it to the block's class:

vue
<template>
    <div :class = 'style'>{{ total }} messages</div>
</template>

<script>
export default {
    props: ['total'],
    setup(props){

        // The variable is not reactive
        var style = 'white'

        return { style }

    }
}
</script>

Listen to changes

Now you need to watch the props and change the style dynamically.

You'll need to use a ref() to force the style variable to be reactive. Otherwise, the setup() function won't return a new value of style after updating it. 😅

vue
<template>
    <div :class = 'style'>{{ total }} messages</div>
</template>

<script>
import { ref, watchEffect } from 'vue'

export default {
    props: ['total'],
    setup(props){

        // Setting as reactive
        var style = ref('white')

        watchEffect(() => {

            // Use props to retrigger the effect on props change
            if(props.total){

                // 1. Configure the style to red
                style.value = 'red'

                // 2. You reset it after 1 sec
                setTimeout(() => style.value = 'white', 1000)

            }

        })

        return { style }

    }
}
</script>

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.