Vuex Reactivity Caveats
Vuex shares the same reactivity caveats regarding property addition as Vue. This CodePen shows how to use
Vue.set
to add a reactive property to a Vuex store. It also presents two failed attempts that I've seen while helping on the Vue Land Discord.
To test the code, select one of the following radio buttons. Each selection triggers different versions of the ADD_PROPERTY mutation.
Only the selection for "Use Vue.set" will allow the property to be added reactively. This means that when you press the Add Property button after making a selection, you'll see the UI update immediately. The other selections won't show the new property or it will only show up later after additional selections are made.
Demonstrating Vue.set Direct Assignment (Won't Work) Replace Array Item (Won't Work)
Press the Select buttons to navigate through different items. Press De-Select to clear the selection.
Item Selected
No Item Selected
{{ $store.getters.selectedItem.id }}
Property obj: {{ $store.getters.selectedItem.obj }}
Property Not Added