Nuxt.js調用asyncData


<template>
  <div>
    Index {{ username }}
  </div>
</template>

<script>
export default {
  name: "Index",
  async asyncData () {
    const asyncData = {};
    await new Promise((resolve, reject) => {
      setTimeout(() => {
        asyncData.username = 'John Smith';
        resolve();
      }, 2000)
    });
    return asyncData;
  }
};
</script>

使用

直接在頁面上使用下面的代碼就行了

{{ username }}

多個請求

async asyncData () {
// 正確
let [pageRes, countRes] = await Promise.all([
  axios.get('/api/users'),
  axios.get('/api/users')
])

  return {
      users: pageRes,
      msg: countRes
    }
 },
created () {
    console.log(this.users)
    console.log(this.msg)
  }
}

高級用法

<template>
  <div>
    <p>postListArray=>{{ postListArray }}</p>
    <p>siteConfigObj=>{{ siteConfigObj }}</p>
  </div>
</template>

<script>
export default {
  name: "Index",
  async asyncData({ $axios }) {
    const siteConfigResult = await $axios.$post(
      "http://www.terwergreen.com/api/site/config/list"
    );
    const postsResult = await $axios.$post(
      "http://www.terwergreen.com/api/blog/post/list"
    );
    const siteConfigObj =
      siteConfigResult.status === 1 ? siteConfigResult.data : {};
    const postListArray = postsResult.status === 1 ? postsResult.data.list : [];

    return { siteConfigObj, postListArray };
  },
  head() {
    return {
      title: this.siteConfigObj.webname + " - " + this.siteConfigObj.webslogen,
      meta: [
        {
          name: "keywords",
          content: this.siteConfigObj.keywords
        },
        {
          hid: "description",
          name: "description",
          content: this.siteConfigObj.description
        }
      ]
    };
  }
};
</script>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM