nuxt 获取数据

asyncData

asyncData钩子只能放在页面组件上,asyncData无法访问组件实例 ( this)
Nuxt.js 会自动将返回的对象与组件数据进行浅合并

<template>
  <div>
    <h1>{{ detail.title }}</h1>
    <p>{{ detail.description }}</p>
  </div>
</template>

<script>
export default {
  async asyncData({ $axios, route }) {
  //拿到路由信息
    const res = await $axios.$get(`/url/${route.params.id}`)
    return res
  },
  data() {
    return {
      detail: {},
    }
  },
}
</script>

fetch

fetch钩子可以放在任何组件上

<template>
  <div>
    <h1>{{ detail.title }}</h1>
    <p>{{ detail.description }}</p>
  </div>
</template>
<script>
export default {
  data() {
    return {
      detail: {},
    }
  },
  async fetch() {
    const res = await this.$axios.$get(`/url/${this.$route.params.id}`)
    this.detail = res
  },
}
</script>

监听路由字符串的更改

<template>
  <div>
    <h1>{{ detail.title }}</h1>
    <p>{{ detail.description }}</p>
  </div>
</template>
<script>
export default {
  data() {
    return {
      detail: {},
    }
  },
 watch: {
    '$route.query': '$fetch'
  },
  async fetch() {
    const res = await this.$axios.$get(`/url/${this.$route.params.id}`)
    this.detail = res
  },
}
</script>
原文地址:https://www.cnblogs.com/heihei-haha/p/14898284.html