I am trying to replace a certain string with a condition before it gets to the output.
Below is my code
<script setup>
import { ref } from 'vue'
const items = ref([{ letter: "A", message: '1' }, { letter: "B", message: '2' }])
</script>
<template>
<li v-for="(item, index) in items">
<p v-if="item.message === '1'">
{{ item.letter }} - {{ 'Apple' }}
</p>
<p v-if="item.message === '2'">
{{ item.letter }} - {{ 'Banana' }}
</p>
</li>
</template>
I tried adding the v-if
inside the v-for
but this seems impractical. I am trying to figure out a way to have item.message
replace its string value before v-for
. Any suggestions?
2
What about a Computed Property?
This derives one value from other values (it’s dependencies). This seems a perfect case here.
You can declared it like this:
import { ref, computed } from 'vue'
const displayItems = computed(() => {
return items.value.map(item => {
if (item.message === '1') {
return `${item.letter} - Apple`
}
if (item.message === '2') {
return `${item.letter} - Banana`
}
return `${item.letter} - unknown`
})
})
And replace your template with this:
<li v-for="item in displayItems">
<span> {{ item }}</span>
</li>