W
W
WebDev2018-06-04 15:02:04
Vue.js
WebDev, 2018-06-04 15:02:04

How to process data in a loop in vue?

Hello,
For example, I have an array of users objects, each field has a timestamp, from which I need to extract the year separately, separately the time.
If it wasn't an array, then I would use computed , but for an array, I define a method and call it in a loop:

<div v-for="user in users">
    <span>{{ getCreatedYear(user.created_at) }}</span>
    <span>{{ user.name }}</span>
    <span>{{ getCreatedTime(user.created_at) }}</span>
</div>

How to process the data in this case?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2018-06-04
@kirill-93

Create a user model

class User {
    // Это позволяет оборачивать в модель данные из API
    // как-то так: `state.users.push(new User(dataFromAPI));`
    constructor({ name, created_at }) {
        this.name = name;
        this.createdAt = created_at;
    }
    
    // Создаёшь нужные методы и геттеры 
    get createdYear() {
        return this.createdAt.getYear();  // или чё там у тебя
    }
}

Voila. No collective farm with filters and methods that you need to copy from component to component or make not-quite-obvious mixins.
<div v-for="user in users">
    <span>{{ user.createdYear }}</span>
    <span>{{ user.name }}</span>
    <span>{{ user.createdTime }}</span>
</div>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question