未获取 Nuxt 组件数据
Nuxt component data not fetched
<template>
<div>
<h1>Index</h1>
<button @click="showMe">BUTTON</button>
</div>
</template>
<script>
export default {
name: 'Index',
async fetch ({ $axios }) {
const result = await $axios.$get('https://api.sampleapis.com/beers/ale')
console.log(result) // show arr that length 100.
this.arr = result
},
data: () => ({
arr: []
}),
methods: {
showMe() {
console.log(this.arr) // show arr that length 0.
}
}
}
</script>
example on the official website同理
但是我的this.arr
没有更新。
我应该怎么做才能解决这个问题?
这真让我抓狂。
为什么?到底为什么?
我的Nuxt版本是2.15.8
fetch(context)
仅适用于页面并且是 deprecated 语法:
Before Nuxt 2.12, there was a different fetch hook that only worked
for page components and didn't have access to the component
instance. If your fetch() accepts a context argument, it will be
treated like a legacy fetch hook. This functionality is deprecated,
and should be replaced with either asyncData or an anonymous
middleware
相反,您应该这样使用它:
async fetch () {
const result = await this.$axios.$get('https://api.sampleapis.com/beers/ale')
console.log(result) // show arr that length 100.
this.arr = result
}
<template>
<div>
<h1>Index</h1>
<button @click="showMe">BUTTON</button>
</div>
</template>
<script>
export default {
name: 'Index',
async fetch ({ $axios }) {
const result = await $axios.$get('https://api.sampleapis.com/beers/ale')
console.log(result) // show arr that length 100.
this.arr = result
},
data: () => ({
arr: []
}),
methods: {
showMe() {
console.log(this.arr) // show arr that length 0.
}
}
}
</script>
example on the official website同理
但是我的this.arr
没有更新。
我应该怎么做才能解决这个问题?
这真让我抓狂。
为什么?到底为什么?
我的Nuxt版本是2.15.8
fetch(context)
仅适用于页面并且是 deprecated 语法:
Before Nuxt 2.12, there was a different fetch hook that only worked for page components and didn't have access to the component instance. If your fetch() accepts a context argument, it will be treated like a legacy fetch hook. This functionality is deprecated, and should be replaced with either asyncData or an anonymous middleware
相反,您应该这样使用它:
async fetch () {
const result = await this.$axios.$get('https://api.sampleapis.com/beers/ale')
console.log(result) // show arr that length 100.
this.arr = result
}