Migrating from Durandal to Vue: Adding Items to shallowRef Array in Vue.js
While doing the conversion from the KnockoutJS/Durandal application to Vue.js I had to convert the observableArrays into shallowRef arrays. The reason I used shallowRefs instead of refs is because I did not need deep reactivity for the objects and shallowRefs fulfills this requirement.
However, I ran into an issue where I was trying to push an object onto a shallowRef array and the UI was not being updated.
I spent some time going through the Vue.js documentation and I found this example on how to update shallowRef arrays:
const shallowArray = shallowRef([
/* big list of deep objects */
])
// this won't trigger updates...
shallowArray.value.push(newObject)
// this does:
shallowArray.value = [...shallowArr.value, newObject]
I created my own function based on this that works for me so far.
/**
* Add a new item to a shallowRef array and update UI/trigger watches
* @param {ShallowRef} shallowRefArr - ShallowRef array to add items to and trigger update
* @param {(any|any[])} newItems - Item or array of items to add to array
*/
function addItemToShallowRefArray(shallowRefArr, newItems) {
let newItemsToUse = Array.isArray(newItems) ? newItems : [newItems];
shallowRefArr.value = [...shallowRefArr.value, ...newItemsToUse]
}
Comments ()