首页 > 解决方案 > VueJS:计算属性在组件中创建之前计算?

问题描述

我有一个组件,它看起来像这样:

export default {
  name: 'todos',
  props: ['id'],
  created () {
    this.fetchData()
  },
  data() {
    return {
    }
  },
  computed: {
    todos () {
      return this.$store.state.todos[this.id]
    }
  },
  methods: {
    async fetchData () {
      if (!this.$store.state.todos.hasOwnProperty(this.id)) {
        await this.$store.dispatch('getToDos', this.id)
      }
    }
  }
}

这就是正在发生的事情:

  1. 该组件接收一个idvia 道具。

当组件加载时,我需要根据 id 获取一些数据

  1. 我有一个created()钩子,我从那里调用一个函数fetchData()来获取数据。

  2. 在方法中,fetchData()函数调度一个动作来获取数据。这将获取数据并将其存储在 Vuex 存储中。

  3. 计算属性todos获取此 id 的数据。

问题是当页面首次加载时,计算的属性todos显示为未定义。如果我更改页面(客户端),那么计算属性会从存储中获取正确的数据并显示它。

我无法理解为什么计算属性不更新?

标签: vue.jsvuejs2vuex

解决方案


您可以使用以下方法:

component.vue(并且只是 render todoItem

  methods: {
    async fetchData () {
      const _this = this;
      if (!this.$store.state.todos.hasOwnProperty(this.id)) {
        this.$store.dispatch('getToDos', {id: this.id, callback: () => {
          _this.todoItem = _this.$store.state.todos[_this.id]
        }});
      }
    }
  }

store.js

  actions: {
    getToDos: (context, payload) => {
      // simulate fetching externally 
      setTimeout(() => {
        context.commit("getToDos__", {newId: payload.id, task: "whatever" });
        payload.callback();
      }, 2000);
    },

推荐阅读