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 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!
CodePudding user response:
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 >
<div >
<div :style="`width: ${wid}%`"></div>
</div>
</div>
<!-- Caption -->
<div >
<p >
Total Staked {{ gems }}/{{ size }} ({{ wid }}%)
</p>
</div>
</div>
</div>