grandnasty
grandnasty

Reputation: 759

Best practices regarding setting properties on data objects in Vue.js?

I am pulling data from an API, suppose the response looks like this

users: [{id: 1, name: 'Daft Punk'}, ...]

and I assign it to the vm by:

this.users = users;

Now, I show these users in a list and would like to toggle some state on a specific user, such as "visible" or "enabled" etc.

Currently I do this:

methods: {
    enableUser: function (user) {
        if (user.enabled === undefined) {
            Vue.set(user, 'enabled', false);
        }
        user.enabled= !user.enabled;
    }
}

I do the

if (user.enabled === undefined) {
    Vue.set(user, 'enabled', false);
}

part since the enabled property is not present in the response object from the API and I want to be able to use that property for v-show and similar things.

Is there a better way of assigning properties that should be reactive? Doesn't feel right writing that snippet for every custom property that I want to use..

Upvotes: 1

Views: 356

Answers (2)

Raj Kamal
Raj Kamal

Reputation: 577

so, you want to add a reactive property to all objects? simplest way would be to make an adapter function eg

//adapter function
function adaptToMyApp(externalObj)
{
    //add extra properties as desired
    externalObj.enabled = false;       
}

// fill users from api.
// and adapt them to your app.
users.forEach(user => adaptToMyApp(user))

// now use users as required

Upvotes: 0

Peter
Peter

Reputation: 12711

If it were me, I'd probably forEach over the data and assign the additional properties before setting it on the view model:

// get data from api, then...
users.forEach(user => user.enabled=true)

this.users = users;

This will keep the rest of your code a lot cleaner - no need to check if the property is defined yet.

Upvotes: 1

Related Questions