【问题标题】:V-For from "Computed" doesn't show up“Computed”中的 V-For 不显示
【发布时间】:2019-12-08 06:23:42
【问题描述】:

我在模板中使用 v-for 来显示计算属性的列表。但即使它在我刷新时工作,当我第一次进入页面时,我也看不到列出的项目。如果我 v-for 我的联系人,我无法过滤。

所以我的数据和计算方法如下所示:

export default {
    data() {
      return {
       contacts: this.$store.getters.loadedContacts,
       search: ""
      };
    },
computed: {
  filterContacts(contacts) {
    return this.contacts.filter(contact => {
      return contact.name.toLowerCase().match(this.search.toLowerCase());
    });
  }   
};

我在我的 HTML 中这样称呼它(filterContacts):

<v-list two-line v-if="contacts">
  <template v-for="(contact, index) in filterContacts">

  <v-list-tile-content>
      <v-list-tile-title>{{ contact.name }}</v-list-tile-title>
        <v-list-tile-action-text>{{ contact.position }}</v-list-tile-action-text>
  </v-list-tile-content>  

  </template>
</v-list>

所以实际的问题是:为什么需要刷新我的页面才能看到 for 循环的结果?
如果我不调用 filterContacs,我将无法使用我的过滤器。

对如何解决过滤和 v-for 循环有什么建议吗?

感谢和抱歉,如果这是一个新手! 非常感谢任何帮助

【问题讨论】:

  • 尝试用this.$store.getters.loadedContacts替换this.contacts.filter
  • 另外,你可以在不同的地方添加虚拟数据,看看它在哪里下降。

标签: vuejs2 computed-properties v-for


【解决方案1】:

组件的数据在创建时设置。 store 中的 getter 可能还没有返回任何数据。

您可以安全地将计算中的this.contacts 替换为this.$store.getters.loadedContacts

您可以选择的另一件事,也许更优雅,是使用 vuex 的 mapGetter 助手。它反应性地将 vuex getter 映射到组件的计算属性(在此处阅读更多信息:https://vuex.vuejs.org/guide/getters.html#the-mapgetters-helper)。

使用 mapGetters,您可以:

...mapGetters({
  contacts: 'loadedContacts'
})

然后从您的数据声明中删除联系人。

【讨论】:

    【解决方案2】:

    谢谢!我实际上观察到了你所说的。事实上,用this.$store.getters.loadedContacts 替换this.contacts 确实解决了我的问题。我还从 data() 中删除了“联系人”。

    谢谢!

    【讨论】:

      猜你喜欢
      • 2019-09-17
      • 2020-06-29
      • 2021-09-26
      • 2019-01-21
      • 1970-01-01
      • 2019-04-02
      • 2019-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多