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>
    
  • 相关阅读:
    linux 下怎么看postgresql安装到哪个目录了?
    sqlserver 存储image 语句
    thinkphp5.1 配置使用
    百度车牌识别demo
    elastticsearch 安装
    InDB开发
    John爆破密码
    域传送漏洞
    新远程下载方式(IME)
    SSH端口转发
  • 原文地址:https://www.cnblogs.com/tangyouwei/p/10558833.html
Copyright © 2011-2022 走看看