[英]How can I process Vue.js props before actually using them?
想象一下以下情況:
我有一個包含2個道具的Menu
組件:
items
filterTerm
Menu
組件不能只顯示項目。它必須首先根據給定的filterTerm
進行過濾。
這提出了兩個問題:
我不知道在顯示items
之前要在哪里處理。 我研究了組件文檔 ,他們似乎沒有提到任何生命周期方法。
是否發生變異所接收到的一個好主意, items
支撐? 除非Vue對每個渲染進行深層克隆(我認為這是不合理的),否則對prop進行突變可能會產生副作用。 因此,我實際上不應該過濾收到的items
。 我應該先克隆它,然后在哪里做呢? 我可以在data:function() { }
做到這一點,但是我的methods
在那里不可用:(
那么,在顯示items
之前過濾items
的正確方法是什么?
我會說計算屬性對此有好處:
讓我們想象一下這些數據:
let raw = [
{
id: 1,
link: '/some-link',
name: 'some-name'
},
{
id: 2,
link: '/other-link',
name: 'other-name'
}
]
並在屬性中獲取此數據的組件:
<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>
如您所見, formated
方法是一個計算屬性,每次raw
屬性更改時都會更新。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.