'Vue3 setup function

I have a problem understanding what the right way is of structuring my Vue3 app.

I am passing a prop called day into my component and would like to calculate the amount of time in percentages that has passed in my compute function. Based on that value I would then like to adjust the width of the progressbar. How do I do this?

I tried the watch hook but it is not finding the progressbar reference.

<template>
    <div class="progress-bar" ref="progressbar">  {{ percentages}}   </div> 
</template>

<script>
import { computed, ref } from "@vue/reactivity";
import { watch} from 'vue'
export default {
    name: 'Progress',
    props:{
        day: Number,
    },
    setup(props){

        const progressbar = ref(null);

        const percentages = computed (() =>{
            return  ( props.day / 14 * 100) .toFixed();
        })
        watch(percentages, () => {
            progressbar.style.width = `${percentages.value}%`;
        })

        return { percentages, progressbar }

    }    

}



Solution 1:[1]

you can try the inline style binding:

<template>
  <div 
    class="progress-bar"
    ref="progressbar"
    :style="{ 'width': percentages + '%' }"
  >{{ percentages }}</div> 
</template>

<script>
import { computed, ref } from "@vue/reactivity";
export default {
    name: 'Progress',
    props: {
        day: Number,
    },
    setup(props) {

        const progressbar = ref(null);

        const percentages = computed(() =>{
            return (props.day / 14 * 100).toFixed();
        })

        return { percentages, progressbar }
    }    
}

the same code a little bit shorter with script setup:

<template>
  <div 
   class="progress-bar"
   ref="progressbar"  
   :style="{ 'width': percentages + '%' }">{{ percentages }}
  </div> 
</template>

<script setup>
import { computed, ref } from 'vue';
const props = defineProps({
  day: Number
})

const progressbar = ref(null);

const percentages = computed(() => props.day / 14 * 100).toFixed())
</script>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1