2
votes

A current project I'm working on uses vuejs extensively and I'm trying to leverage Lodash for access to some basic array helper functions. On a simple "like" style button I have the following in a vue template:

<button class="btn btn-xs" v-bind:class="appreciated" v-on:click="toggleAppreciate()"><i class="fa fa-heart"></i> Appreciate</button>

The computed property looks like this:

appreciated: function()
{
    return _.indexOf(this.global.userAppreciates, this.entity_id) > -1 ? 'btn-primary' : 'btn-default'
}

Clicking the button sends a simple ajax request and the server responds with the toggle status of "added" or "removed". I'm using the following code to then mutate a store of "appreciates":

if (response.data.type === 'added')
{
    return this.global.userAppreciates.push(this.entity_id)
}

return _.pull(this.global.userAppreciates, this.entity_id)

The added method that uses plain javascript works fine. Looking in vuetools shows that the number of elements in the userAppreciates has been updated and the button does change state. However - using Lodash's _.pull method to remove the element from the array doesn't toggle the computed property state even though the element is removed from the store. If I use plain javascript and do something like this, however:

let index = this.global.userAppreciates.indexOf(this.entity_id)
this.global.userAppreciates.splice(index, 1)

The store is also updated - but the computed property does change state and the button class changes.

Is there something specifically in the way Lodash handles these methods that causes Vuejs not to pick up on a property change? Any clarification would be appreciated.

1

1 Answers

1
votes

All the array related changes may not be reactive. Docs list following docs which are reactive:

  • push()
  • pop()
  • shift()
  • unshift()
  • splice()
  • sort()
  • reverse()

I will suggest to use above methods and implement _.pull using above methods, which should invoke compluted.