Reputation: 25
I’m having trouble figuring out the best way to use variable returned by vue functions in CSS inline styles, in this case the “width” style.
I have 2 variables being returned to the template that I can use with the {{}} syntax, but not as a CSS style.
This works fine:
Total Staked {{ gems }}/{{ size }} ({{
Math.round((gems / size) * 100)
}}%)
This looks like this when rendered: Total Staked 200/350 (57%)
I would like to put that calculated percentage (57%) into css inline style like this:
<div class="bg-black h-2 rounded-md text-white" style="width: 57%"></div>
where the width: 57% is populated dynamically.
I am using Vue 3 with Tailwind CSS
Here is a Codepen: https://codepen.io/johnwinsor/pen/RwxvdZZ
Thank you!
Upvotes: 2
Views: 648
Reputation: 23480
You can create computed property and bind your style:
new Vue({
el: "#app",
data() {
return {
gems: 300,
size: 350
};
},
computed: {
wid() {
return Math.round((this.gems / this.size) * 100)
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css" integrity="sha512-wnea99uKIC3TJF7v4eKk4Y+lMz2Mklv18+r4na2Gn1abDRPPOeef95xTzdwGD9e6zXJBteMIhZ1+68QC5byJZw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<div id="app">
<div>
<!-- Thermometer -->
<div class="w-2/3 h-2 pl-5 pr-5 m-auto">
<div class="w-full h-2 mt-6 mb-2 bg-red-500 rounded-md">
<div class="bg-black h-2 rounded-md text-white" :style="`width: ${wid}%`"></div>
</div>
</div>
<!-- Caption -->
<div class="flex flex-wrap justify-center align-center pb-5">
<p class="text-red-600">
Total Staked {{ gems }}/{{ size }} ({{ wid }}%)
</p>
</div>
</div>
</div>
Upvotes: 2