简体   繁体   中英

How can I process Vue.js props before actually using them?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM