【问题标题】:Component not updating properties组件不更新属性
【发布时间】:2022-01-13 04:27:38
【问题描述】:

我有两个组成生物体:

  • 过滤器组件
  • 表格组件

这两个组件都将呈现在一个页面中。
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>

我不知道为什么当我在我的方法中调用道具时我的组件没有更新道具,但是如果我将其渲染或打印到 vue 模板中,组件会正确更新。

PS:我使用的是 nuxt v2.11。

【问题讨论】:

    标签: javascript vue.js nuxt.js reactive-programming


    【解决方案1】:

    你没有在filter-component中绑定filter


    直接更新 props 不是一个好主意,可能会导致错误。

    为您的子组件使用computed,而不是直接更新道具

    过滤器组件

    // 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" />
    

    【讨论】:

    • 啊,我明白了,感谢您抽出宝贵时间@Dengsihan,但过滤器值不仅包含文本字段。这就是我不使用 v-model/vue 绑定的原因。但我正在使用这种方法解决我的代码。
    • @ikbalmaulana 不改变道具很重要,正如邓所说。如果你想要一些干净的代码,请使用 ESlint 并遵循指南。
    猜你喜欢
    • 1970-01-01
    • 2011-06-02
    • 2019-07-03
    • 1970-01-01
    • 1970-01-01
    • 2016-06-11
    • 2017-11-18
    • 2015-04-12
    • 1970-01-01
    相关资源
    最近更新 更多