javascript - VueJS - Axios 数组未更新

标签 javascript html arrays vue.js axios

我正在尝试通过 API 更新我在数据中声明的数组。当我用一个对象初始化数组时,这个对象在 HTML 代码中显示得很好。似乎在 axios 调用范围之后数组没有“保存”。任何人都可以帮助我吗?我没有任何错误代码/消息。

var vm = new Vue({
el: '#recettes',
data: {
  results: []
},
created() {
  axios.get('url')
  .then((response) => {
    this.results = response.data
    console.log("Size before end of scope = " + this.results.length)  // = 4
  });
  console.log("Size after = " + this.results.length) // = 0
}
});

响应 API 是:

[
  {
    "id": 1,
    "titre": "Cassoulet",
    "contenu": "Couper. Faire cuire...",
    "id_util": 1
  },
  {
    "id": 2,
    "titre": "Gateau",
    "contenu": "chocolat",
    "id_util": 4
  },
  {
    "id": 3,
    "titre": "Gateau",
    "contenu": "fraise",
    "id_util": 5
  },
  {
    "id": 4,
    "titre": "Gateau",
    "contenu": "Mélanger, cuire, four 220°...",
    "id_util": 5
  }
]

模板:

    <div id="recettes">
    <div v-for="result in results">
      <div class="card">
        <div class="card-divider">
          {{ result.titre }}
        </div>
        <div class="card-section">
          {{ result.contenu }}
        </div>
      </div>
    </div>
    </div>

更新

var vm = new Vue({
  el: '#recettes',
  data: {
    results: []
},
created() {
  axios.get('URL')
  .then(response => {
    this.results = response.data
    console.log("size: " + this.results.length)
    console.log('results[0]: ' + this.results[0].titre)
  })
}
});

使用此代码,results[0].titre 包含正确的字符串。但是在 HTML 代码中,没有显示卡片。 并使用此代码:

var vm = new Vue({
  el: '#recettes',
  data: {
    results: [
      {"id" = 1, "id":1,"titre":"Cassoulet","contenu":"Couper. Faire cuire...","id_util":1}
    ]
},
created() {
  axios.get('URL')
  .then(response => {
    this.results = response.data
    console.log("size: " + this.results.length)
    console.log('results[0]: ' + this.results[0].titre)
  })
}
});

一张卡片在 HTML 中显示为 titre = "Cassoulet"和 contenu = "Couper. Faire cuire..."

这就是为什么我说好像数组没有更新...

最佳答案

您好,我认为这是一个异步问题。如您所见,javascript 不会等待另一个函数完成。试试这个。

created() {
  axios.get('url')
  .then((response) => {
    this.results = response.data
    console.log("Size before end of scope = " + this.results.length)  // = 4
    return true;
  }).then((response) => {
      console.log("Size after = " + this.results.length) // = 4
  });
  // console.log("Size after = " + this.results.length) // = 0
}

UPDATE1:添加了 fiddle

这是一个示例 fiddle 供您查看。 https://jsfiddle.net/khenxi/n49zj258/

关于javascript - VueJS - Axios 数组未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44447943/

相关文章:

javascript - 将 javascript 对象转换到 Controller 的模型中

javascript - jQuery 用户界面 : Before start draggable

javascript - jQuery 解析巨大的响应失败

iOS 将文件行读入数组

c - C 中删除数组中的空格?

javascript - fullpage.js 只会在窗口调整大小后滚动溢出

javascript - echo onClick 后删除 sql 行

javascript - 通过引用和拼接传递

javascript - Firefox 的图像加载失败,但 Chrome、Edge 和 IE 运行良好

javascript - HTML 5/站点配置导致 FB block