zoukankan      html  css  js  c++  java
  • 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>
    
  • 相关阅读:
    phpcms v9 更改首页
    不是技术牛人,如何拿到国内IT巨头的Offer
    超实用的PHP代码片段!
    Android 中的 Service 全面总结
    近期十大优秀jQuery插件推荐
    DIOCP之编写第一个应用程序(二)
    DIOCP之编写第一个应用程序(一)
    DIOCP之DEMO学习顺序及达到要求
    DIOCP之EchoServer分析
    DIOCP之数据接收事件
  • 原文地址:https://www.cnblogs.com/tangyouwei/p/10558833.html
Copyright © 2011-2022 走看看