我有兩個組成部分:
- 過濾器組件
- 表組件
這兩個組件都將呈現在一個頁面中。
filter 組件會將 props 傳遞給 table 組件以更新 table 中的資料。這是我的代碼的簡單部分。
FilterComponent
passUpdateToParent() {
this.$emit("update", this.filter) // I just emit this variable
},
processResetFilter() {
this.filter = {
search: {},
value: ""
}
this.passUpdateToParent()
},
TableComponent
...
props : {
filter: {default : () => ({}),
... // another props
},
methods:{
testGetFilter(){
console.log(this.filter) // this props not update if I call in one time, but when I call in twice this props updated.
}
}
<template>
<section>
{{ filter }} <!-- updated properly -->
</section>
</template>
PageComponent
components: {
FilterComponent: () => import("@/components/FilterComponent"),
TableComponent: () => import("@/components/TableComponent"),
},
data :() => ({
filter :{}
}),
methods : {
processGetFilter(value){
this.filter = value
},
}
<template>
<section>
<filter-component @update="processGetFilter" />
<table-component :filter="filter" />
</section>
</template>
我不知道為什么我的組件在我的方法中呼叫 props 時沒有更新 props,但是如果我正在渲染或將它列印到 vue 模板中,組件會正確更新。
PS:我使用的是 nuxt v2.11。
uj5u.com熱心網友回復:
你沒有系結filterinfilter-component
直接更新 props 不是一個好主意,這可能會導致錯誤。
使用computed你的子組件,而不是dircetly更新道具
過濾器組件
// update the computed filter instead of props value
<input v-model="filter.value"/>
....
props: {
value: {
default: () => {}
}
},
computed: {
filter: {
get() {
return this.value;
},
set(newFilter) {
this.$emit('input', newFilter)
}
}
}
在您的PageComponent 中:
<filter-component v-model="filter" />
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/377021.html
