javascript - 如何在运行时访问 vue 实例数据
问题描述
我的问题很简单,我想在运行时分配数据并在 vue 实例中再次获取它们
data() {
return {
panels:[],
};
},
created() {
this.fetchPanels();
//console.log(this) , i can find panels already assigned in this instance
//console.log(this.panels) , it gives me zero array
},
methods: {
fetchPanels() {
this.$http
.get(Shared.siteUrl+"/api/" + this.category_title + "/panels")
.then(function(response) {
this.panels = response.body.data;
});
},
解决方案
如果你打算使用 async/await(我同意你应该这样做),你也应该为 http 调用这样做。await somefunc().then()
感觉风格混搭不好。这具有更短的优点。
data() {
return {
panels:[],
};
},
async created() {
await this.fetchPanels();
console.log(this.panels);
},
methods: {
async fetchPanels() {
const response = await this.$http.get(Shared.siteUrl + "/api/" + this.category_title + "/panels")
this.panels = response.body.data;
},
请记住,Vue 生命周期不会等待您的异步生命周期钩子。在这个例子中这不会是一个问题,但记住这一点绝对是好的。即,如果您添加
mounted() {
console.log(this.panels);
},
它会空出来,因为异步任务created()
现在将在之后发生mounted()
推荐阅读
- neo4j - Neo4j 过滤状态
- streaming - apache flink 检查点已完成但未完成
- pytest - 如果测试文件具有设置和拆卸部分,如何使用 pytest 并行执行测试
- ios - 如何在 iOS 应用启动期间访问 IMvxLog
- angular - 如何正确编辑显示在网格中的值?
- powershell - Azure 管道:基于 OS 的条件环境变量
- android - 如何在屏幕触摸和按住上进行 Activity 更改,并在释放相同的保持时再次更改?
- java - 根据文件中的多个模式从文件中提取字符串
- android - 在错误的包中生成的数据绑定
- firebase - 动态链接和托管不同意自定义域是否正确连接