1

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 }

    }    

}

1 Answer 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>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. That worked! I didn't know one could bind to the style property. Great framework!

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.