1

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..

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Will think about this. Do you know of any other ways?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.