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>
posted @ 2019-03-19 15:12  灯塔下的守望者  阅读(9246)  评论(1编辑  收藏  举报