首页 > 解决方案 > 如何在运行时访问 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;
        });
    },

标签: javascriptvuejs2

解决方案


如果你打算使用 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()


推荐阅读