3

Imagine the following situation:

I have a Menu component with 2 props:

  • items
  • filterTerm

The Menu component can't just simply display the items.. It has to filter it first according to the given filterTerm.

This raises 2 questions:

  1. I don't know where to process items before displaying them. I've researched the Components documentation and they don't seem to mention any life-cycle methods.

  2. Is it a good idea to mutate the received items prop? Unless Vue performs a deep clone on every render, which I find unreasonable, mutating a prop may have side-effects. Therefore, I shouldn't actually filter the received items. I should clone it first, but then where would I do it? I could do it in the data:function() { } but then my methods are not available there :(

So, what is the proper way of filtering the items before displaying them?

1 Answer 1

6

I would say that computed properties are good for that:

Let's imagine this data:

let raw = [
    {
        id: 1,
        link: '/some-link',
        name: 'some-name'
    },
    {
        id: 2,
        link: '/other-link',
        name: 'other-name'
    }
]

And that component that takes this data in property:

<template>
    <div>
        <ul>
            <li v-for="item in formated"><a :href="item.href">{{ item.libel }}</a></li>
        </ul>
    </div>
</template>

<script>
    export default {
        props: ['raw'],
        computed: {
            formated () {
                let menu = []
                for(let i  0; i < this.raw.length; i++) {
                    menu.push({
                        libel: this.raw[i].name,
                        href: this.raw[i].link
                    })
                }
                return menu
            }
        }
    }
</script>

As you can see, the formated method is a computed property that will update each time your raw property change.

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

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.