cklmercer / vue-stash

Easily share reactive data between your Vue components.
MIT License
403 stars 29 forks source link

Reactivity with Arrays #3

Closed matt-allan closed 7 years ago

matt-allan commented 8 years ago

Hello,

Thanks for the plugin, it's exactly what I was looking for 👍

Is there any way the plugin could extend arrays in the store with $set like Vue does? Right now I'm having to use splice to keep the store reactive for arrays.

cklmercer commented 8 years ago

Let me dig into the vue core a little and see if I can't figure out how it's handling that. Do you have an example of how you'd like to see this work? Some sample usage would be very helpful.

matt-allan commented 8 years ago

The issue I'm having is that updating the store like this:

this.users[0] = 'John Doe';

...will not work. It updates the store but Vue doesn't realized it was updated, so the reactivity doesn't work. Ideally I could use the method $set like I can for any Vue data properties to update the array.

Here is an example based on the README examples.

store.js:

export default {
    users: ['Cody', 'Evan']
}

Using set in a component:

Vue.component('user-card', {
    store: ['users'],
    ready() {
        console.log(this.users[0]); // 'Cody'
        this.users.$set(0, 'John Doe');
        console.log(this.users[0]); // 'John Doe'
    }
});

Hopefully that makes sense, let me know if you need more examples.

cklmercer commented 8 years ago

Thanks for the example! I understand much better now. I'll see what I can do.

cklmercer commented 8 years ago

Sorry I haven't gotten to this yet. Pretty slammed preparing for a presentation I'm giving soon. Promise I'll get to it as soon as things settle down.

tomByrer commented 7 years ago

When I first read about the reactive updates, I thought of freezer, but seems that they pivot before updates.

I could see where this.users[0] = 'John Doe'; would be useful.

cklmercer commented 7 years ago

I'm still trying to figure out how best to handle this. I've figured out some background solutions, but I haven't been able to spend a lot of time on it.

cklmercer commented 7 years ago

The simplest solution is to just use the Vue.set like you normally would.

Let's assume we have a store object that looks like this,

{
  users: [
    'john doe',
    'cody mercer',
  ]
}

And now let's assume we want to add a user to the 2 index, and also update the user at index 0.

We can do the following..

$vm.$set($vm.users, 2, 'new guy')
$vm.$set($vm.users, 0, 'I changed my name')

Hope this helps. I'm totally open to accepting a PR for a better solution, but I've yet to be able to come up with anything that can handle this auto-magically.

vthunder commented 5 years ago

This problem bit me recently. Your workaround works well—maybe it could be noted on the main README?