【问题标题】:VueJS data from nested Axios requests not rendering in view来自嵌套 Axios 请求的 VueJS 数据未在视图中呈现
【发布时间】:2019-01-06 06:55:41
【问题描述】:

我正在尝试使用 VueJS 和 Axios 在页面上列出来自 API 的一组帖子。我面临的问题是需要通过针对该特定帖子的单独 API 调用来检索一段数据(帖子 url),并且它们在初始 API 调用中提供该数据的 url。我的第一部分工作得很好,但是当值 is 出现在 Vue devtools 中时,我无法在视图中渲染 href。

JS

const vm = new Vue({
  el: '#app',
  data: {
    posts: []
  },
  mounted() {
    this.getPosts();
  },
  methods: {
    getPosts() {
      axios.get("api_url")
      .then((response) => {
        this.posts = response.data.posts;
        // Get URL for each post from separate API call
        this.posts.map(post => {
          axios.get(post.details_url+"&output=json")
          .then((response) => {
            post.official_url = response.data.post.pet_details_url;
          }).catch( error => { console.log(error); });
        });
      }).catch( error => { console.log(error); });
    }
  }
});

HTML

<div id="app">    
  <div v-for="post in posts">
    <a :href="post.official_url"> //href won't render
      <h2>{{ post.title }}</h2>
      <p>{{ post.text }}</p>
    </a>
  </div>
</div>

数据显示在 Vue DevTools 中

【问题讨论】:

  • 添加&lt;div v-for="post in posts" :key="something_unique"&gt;可能会解决您的问题
  • 感谢@TruongDang 的建议,但添加密钥并没有帮助。 ://
  • 看起来很奇怪,我总是使用像 :href= "`/${post.official_url}`" 这样的 href 并且它可以工作。确保您的 post.official_url 不为空 :"(
  • 我将其更改为该格式,现在出现了 href,但我得到了 &lt;a href="undefined"&gt;&lt;/a&gt;。所以我认为我的问题更多地与我在 JS 中的设置方式有关。

标签: vue.js axios


【解决方案1】:

可能是reactive problem。你可以试试Vue.set

getPosts() {
    let vm = this
    axios.get("api_url")
    .then((response) => {
      this.posts = response.data.posts;
      // Get URL for each post from separate API call

      this.posts.map((post, index) => {
        axios.get(post.details_url+"&output=json")
        .then((response) => {
          post.official_url = response.data.post.pet_details_url;
          Vue.set(vm.posts, index, JSON.parse(JSON.stringify(post)))
        }).catch( error => { console.log(error); });
      });
    }).catch( error => { console.log(error); });
  }

【讨论】:

  • 谢谢!这解决了我的问题。另外,感谢您链接解释,我仍在学习 VueJS,所以这是非常感谢的信息。
猜你喜欢
  • 2020-04-21
  • 2016-05-13
  • 2021-05-01
  • 2019-10-16
  • 1970-01-01
  • 1970-01-01
  • 2020-06-21
  • 2014-10-07
  • 2021-08-11
相关资源
最近更新 更多