Vue.js Object Dict Reactivity

Aug 21, 2018
New attribute/property changes not detected

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 computed selectName.
  • Subsequent changes to this.findItems[4] = 'Unknown' is not reflected through computed selectName reactivity. For this to work properly, adding of new object property/attribute should be done through Vue.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:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.