vue.js - 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)
}
}
}
}
这就是正在发生的事情:
- 该组件接收一个
id
via 道具。
当组件加载时,我需要根据 id 获取一些数据
我有一个
created()
钩子,我从那里调用一个函数fetchData()
来获取数据。在方法中,
fetchData()
函数调度一个动作来获取数据。这将获取数据并将其存储在 Vuex 存储中。计算属性
todos
获取此 id 的数据。
问题是当页面首次加载时,计算的属性todos
显示为未定义。如果我更改页面(客户端),那么计算属性会从存储中获取正确的数据并显示它。
我无法理解为什么计算属性不更新?
解决方案
您可以使用以下方法:
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);
},
推荐阅读
- android - 从微调器中获取条件,并根据该条件从数据库中检索并列出列表视图中的数据
- microservices - 微服务和复制数据库表
- python - 如何使用 SQLAlchemy 的 `one_or_none` 查询方法?
- python - 如何在python中组合两个具有相同索引的系列?
- spring-boot - 在 Spring Boot 中使用无默认构造函数和最终字段进行 Bean 初始化
- java - 如何解析输入 JSON,并基于代表产品库存的现有 JSON 生成账单
- html - Buycraft ::从左边保持之前
- windows - Oracle 12c 安装问题
- python - 使用 python 2 和 smtplib 发送电子邮件时出错
- c++ - 将粒子投射到立方体的表面