组件不更新属性
Component not updating properties
我有两个组成生物:
- 过滤器组件
- 表格组件
这两个组件将呈现在一个页面中。
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.
您没有在 filter-component
中绑定 filter
直接更新道具不是一个好主意,这可能会导致错误。
对你的子组件使用 computed
而不是直接更新 props
过滤器组件
// 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" />
我有两个组成生物:
- 过滤器组件
- 表格组件
这两个组件将呈现在一个页面中。
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.
您没有在 filter-component
filter
直接更新道具不是一个好主意,这可能会导致错误。
对你的子组件使用 computed
而不是直接更新 props
过滤器组件
// 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" />