简体   繁体   English

在实际使用Vue.js道具之前,我该如何处理它们?

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

Imagine the following situation: 想象一下以下情况:

I have a Menu component with 2 props: 我有一个包含2个道具的Menu组件:

  • items
  • filterTerm

The Menu component can't just simply display the items.. It has to filter it first according to the given filterTerm . Menu组件不能只显示项目。它必须首先根据给定的filterTerm进行过滤。

This raises 2 questions: 这提出了两个问题:

  1. I don't know where to process items before displaying them. 我不知道在显示items之前要在哪里处理。 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? 是否发生变异所接收到的一个好主意, items支撑? Unless Vue performs a deep clone on every render, which I find unreasonable, mutating a prop may have side-effects. 除非Vue对每个渲染进行深层克隆(我认为这是不合理的),否则对prop进行突变可能会产生副作用。 Therefore, I shouldn't actually filter the received items . 因此,我实际上不应该过滤收到的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 :( 我可以在data:function() { }做到这一点,但是我的methods在那里不可用:(

So, what is the proper way of filtering the items before displaying them? 那么,在显示items之前过滤items的正确方法是什么?

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. 如您所见, formated方法是一个计算属性,每次raw属性更改时都会更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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