I use a findItems
object prop to store items by key.
const findItems = { 1: 'Apple', 2: 'Orange', 3: 'Durian'}
<template> <div> {{ selectName }} <a href="#" @click.prevent="addItem">Click to Add</a> </div></template>
export default { props: ['select', 'findItems'], computed: { selectName() { this.findItems[select] } }, methods: { addItem() { this.findItems[4] = 'New Fruit' this.select = 4 } }}
Observations
- Adding new item by calling
this.findItems[4] = 'New Fruit'
seems to work properly in computedselectName
. - Subsequent changes to
this.findItems[4] = 'Unknown'
is not reflected through computedselectName
reactivity. For this to work properly, adding of new object property/attribute should be done throughVue.set(findItems, 4, 'New Fruit')
instead of direct assignment. - Changes to existing object property/attribute using
this.findItems[1] = 'Change Apple'
seems to work fine without any problem.
References: