If the "const local (const local = localStorage.getItem("key");" is equal to "name_jp", then change the "card.name_en" to "card.name_jp" which is inside the span tag. How can I do this effectively and correctly?
***Sorry for my bad English
<div v-for="card in list" :key="card.id">
<span id="name">
<span > </span> {{ card.name_en }}</span>
</div>
</div>
</div>
</template>
<script>
import { computed } from "vue";
import { lan } from "@/modules/languages";
import useCards from "@/modules/geral";
export default {
setup() {
const cards = useCards();
const list = computed(() => cards.state.details);
const local = localStorage.getItem("key");
return {
list,
lan,
local,
};
CodePudding user response:
Just add computed getter for this field:
setup() {
const cards = useCards();
const list = computed(() => cards.state.details);
const local = localStorage.getItem("key");
const localizedName = computed(() => (card) => {
if (local === 'jp') {
return card.name_jp
} else {
return card.name_en
}
})
return {
list,
lan,
local,
localizedName,
};
}
And use it as:
<span > </span> {{ localizedName(card) }}</span>
Note that changing the value in localStorage
does not redraw the component. The localStorage.getItem('key')
is not a reactive property; therefore, each change must be accompanied by a redrawing of the component. Alternatively, you can use, for example, the useLocalStorage
from the vueuse
. This will help make the local
values reactive:
setup() {
const cards = useCards();
const list = computed(() => cards.state.details);
const local = useLocalStorage("key");
const localizedName = computed(() => (card) => {
if (local.value === 'jp') {
return card.name_jp
} else {
return card.name_en
}
})
return {
list,
lan,
local,
localizedName,
};
}