NUXT 3 在客户端获取数据

Ser*_*nov 4 vue.js vuejs3 nuxtjs3 nuxt3

例如,我们有 posta api,它可以返回帖子(获取)并创建新帖子(帖子)。

首先我需要将它们放在服务器端。我就是在asyncData选项上这样做的。我使用useFetch可组合来防止$fetch双重数据获取。 https://nuxt.com/docs/api/utils/dollarfetch

好的,我有服务器端获取的发布数据。但现在我希望能够使用options api 方法添加一些数据。

我的函数是否应该带有异步前缀,或者如果我只在客户端使用它,那就不必要了?如果我只想在客户端使用该功能,我应该使用哪种方法来发布一些数据?

export default defineNuxtComponent({
   
    async asyncData () {
        return {
            posts: useFetch ('/api/posts')['data']
        }
    },

   methods:{
    post(event : Event) {
        event.preventDefault();

        // post form data to api

       $fetch('/api/posts',{
            method: 'POST',
            body: JSON.stringify(this.form)
        })
        // this.posts.push(data);

    
    },
}
Run Code Online (Sandbox Code Playgroud)

正在使用

 the $fetch('/api/posts',{
            method: 'POST',
            body: JSON.stringify(this.form)
        }) 
Run Code Online (Sandbox Code Playgroud)

是正确的方法吗?之后我如何刷新客户端的帖子。就像是

axios.post().then(data)=>{this.posts.push(data)} 
Run Code Online (Sandbox Code Playgroud)

在官方文档https://nuxt.com/docs/getting-started/data-fetching中 说:

useFetch、useLazyFetch、useAsyncData 和 useLazyAsyncData 仅在安装或生命周期挂钩期间工作

在 nuxt 模块站点https://axios.nuxtjs.org/中 说:

Axios 模块支持 Nuxt 2。Nuxt 3 用户可以使用新的同构 $fetch API(迁移指南)。

那么我是否应该在客户端获取期间使用 $fetch 、 useFetch、 useLazyFetch、 useAsyncData 和 useLazyAsyncData ?

我在 nuxt3 文档中找不到任何在单击按钮等方法中使用 fetch 的示例。

And*_*hiu 7

以下是您的组件的示例:

<template>
  <div>
    <input v-model="form.searchTerm" />
    <input v-model.number="form.pageSize" type="number" />
    <button @click="getPosts">Get posts</button>
  </div>
  <template v-if="posts.length">
    <div v-for="post in posts" :key="post.id">
      <pre v-text="JSON.stringify(post, null, 2)" />
    </div>
  </template>
</template>
<script setup>
const posts = ref([])

const form = reactive({
  searchTerm: '',
  pageSize: 25
})

const getPosts = async () => {
  const { data } = await useFetch('/api/posts', {
    method: 'POST',
    body: JSON.stringify(form)
  })
  posts.value = data || []
}

// if you want fetch when component mounts:
onMounted(getPosts) 
</script>
Run Code Online (Sandbox Code Playgroud)

该模板非常基本,但它应该让您了解它如何使用数据以及它是如何工作的。
修改form以使用后端期望的任何查询参数。


更新:虽然上面是Nuxt3中推荐的方式,但Options API仍然可用。这应该可以做到:

export default {
  data: () => ({
    posts: []
  }),
  methods: {
    async getPosts() {
      const { data } = await $fetch('/api/posts', {
        method: 'POST',
        body: JSON.stringify(this.form)
      })
      this.posts = data
    }
  }
}
Run Code Online (Sandbox Code Playgroud)