I know how to implement what I am about to ask in a few different ways, I am wondering what the best way to do this is, and by that I mean the least expensive, most efficient way from a javascript perspective.
If I create a table that lists a size guide for t-shirts, this isn't going to change for all the t shirts in a store, so the size guide will be mostly static. I see two solutions at the moment and I feel there is a better way to do this.
The first way would be to create two tables and toggle the display: none
, which I don't like. Another way is to take each value, parseFloat and then multiply each value by 2.54. The last I can think of would be to set up something like this:
Vue.createApp({
name: 'size guide app',
data() {
return {
isMetric: false
}
}
})
then in the markup
<table>
<tbody>
<tr>
<!-- Do this for each cell-->
<td>
<span v-if="isMetric">90 cm</span>
<span v-else>35.4 in</span>
</td>
</tr>
</tbody>
</table>
For a basic size guide with about 50 cells, is this redundancy with v-if
/v-else
wrong and can this posted solution be improved in any way?
CodePudding user response:
You can also create a computed property and return desired values:
const app = Vue.createApp({
name: 'size guide app',
data() {
return {
isMetric: false,
items: [90, 80, 70, 60]
}
},
computed: {
getItems() {
return this.isMetric ? this.items.map(i => i ' cm') : this.items.map(i => ((i/2.54).toFixed(1)) ' in')
}
}
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
<button @click="isMetric = !isMetric">switch</button>
<table>
<tbody>
<tr v-for="item in getItems">
<td>
{{ item }}
</td>
</tr>
</tbody>
</table>
</div>
CodePudding user response:
Your first option is doable with vue's v-show
instead of v-if
which has largely the same usage as v-if
but function's via display: none
:
In comparison, v-show is much simpler - the element is always rendered regardless of initial condition, with CSS-based toggling.
Generally speaking, v-if has higher toggle costs while v-show has higher initial render costs. So prefer v-show if you need to toggle something very often, and prefer v-if if the condition is unlikely to change at runtime.
In terms of performance, you're unlikely to see any major difference with how small the DOM diff is (which is mostly saved via v-show
), but both carrying the same repaint cost.