[Nuxt] Load Data from APIs with Nuxt and Vuex

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Nuxt] Load Data from APIs with Nuxt and Vuex相关的知识,希望对你有一定的参考价值。

In a server-rendered application, if you attempt to load data before the page renders and the data fails to load, your application will not run unless you handle the error properly. This lesson walks you through the options of handling load errors so that your users will always have a good experience.

 

<template>
  <article class="pa3 pa5-ns">
    <ul class="list pl0 ml0 center mw6 ba b--light-silver br2">
      <li v-for="todo of todos" class="ph3 pv3 bb b--light-silver">{{todo.task}}</li>
    </ul>
  </article>
</template>

<script>
  import { mapState } from ‘vuex‘
  import axios from ‘axios‘

  export default {

    async fetch ({store, redirect}) {
      try {
        const res = await axios.get(‘https://todos-cuvsmolowg.now.sh/todoss‘)
        store.commit(‘init‘, res.data)
      } catch (err) {
        redirect(‘/error‘)
        // store.commit(‘init‘, [])
      }
    },
    computed: {
      ...mapState({
        todos: (state) => state.todos
      })
    }
  }
</script>

 

There are three ways to handle loading data error:

1. try catch the async await:

      try {
        const res = await axios.get(‘https://todos-cuvsmolowg.now.sh/todoss‘)
        store.commit(‘init‘, res.data)
      } catch (err) {
        store.commit(‘init‘, [])
      }

 

2. Redirect to a error page:

<template>
  <p>
    There are some errors
  </p>
</template>

    async fetch ({store, redirect}) {
      try {
        const res = await axios.get(‘https://todos-cuvsmolowg.now.sh/todos‘)
        store.commit(‘init‘, res.data)
      } catch (err) {
        redirect(‘/error‘)
      }
    },

 

3. Default error page:

    async fetch ({store, redirect, error}) {
      try {
        const res = await axios.get(‘https://todos-cuvsmolowg.now.sh/todos‘)
        store.commit(‘init‘, res.data)
      } catch (err) {
        error({
          statusCode: 500,
          message: ‘Something happened on server‘
        })
      }
    },

 

以上是关于[Nuxt] Load Data from APIs with Nuxt and Vuex的主要内容,如果未能解决你的问题,请参考以下文章

Bigquery API:如何为 load_table_from_storage 调用提供架构

Flutter, Android Unable to load Maven meta-data from ~ Build error 解决方法

使用 load_table_from_dataframe 方法将数据写入 BigQuery 表错误 - 'str' 对象没有属性 'to_api_repr'

Cannot load keys from store: class path resource [keystore.jks]

Nuxt.js asyncData 多请求

无法在 Nuxt 组件中使用 axios 从 api 获取数据