例如,我们有Posta API,它可以返回帖子(GET)和创建新帖子(POST).

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

好的,我已经从服务器端得到了帖子数据. 但现在我希望能够使用methods options api添加一些数据.

我的函数应该加async个前缀,或者如果我只在客户端使用它,那是不必要的? 如果是i want to use the funtion only on the client side,我应该用什么方法来发布一些数据?

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);

    
    },
}

正在使用

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

这条路对吗? 之后我如何在客户端刷新帖子.像这样的东西

axios.post().then(data)=>{this.posts.push(data)} 

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

UseFetch、useLazyFetch、useAsyncData和useLazyAsyncData只能工作 在设置或生命周期挂钩期间

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

Axios模块支持Nuxt2.Nuxt3用户可以使用新的同构 $FETCH API(迁移指南).

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

我在nuxt3文档中找不到任何在方法中使用Fetch的例子,比如点击按钮等.

推荐答案

下面是组件外观的一个示例:

<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>

The template is quite basic, but it should give you an idea on how it's using the data and how it all works.
Modify form to use whatever query params your backend expects.


更新:虽然以上是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
    }
  }
}

Vue.js相关问答推荐

在Nuxt项目中混合Scrolltrigger与Lenis

Visual Studio代码中的VUE/VLAR扩展不断崩溃:JS/TS语言服务立即崩溃5次…

具有VUE身份验证的Azure AD

如何在与父集合相同的读取中取回子集合(或重构数据?)

Vue Router中.getRoutes()获取的路由顺序优化建议

Vue 3使用计算(computed)属性对象获取图像信息,在模板中呈现值时变为NaN

在 onMounted 之前渲染的 Vue 模板

我在表格中创建了一个包含信息的新行,但在 Cypress e2e 测试中我无法获得最后一行(新行)

在 Ajax 函数中访问 Vue.js 组件属性

Vuetify grid layout - 如何填充网格中元素的高度

我可以在未注册的组件上构建 Vue.js 失败吗?

Object.assign 没有正确复制

如何为 Vue 项目设置 lint-staged?

在 Vuejs 中计算 DOM 元素之间距离的最佳方法是什么?

交换数组项

如何使用 JavaScript 按索引删除数组元素?

在 VueJS 中使用 Axios - 这个未定义

Vue js在列表中添加动态字段,删除和排序不起作用

VS Code - 在 .vue 文件中启用 autoClosingTags 选项

带有 Firebase 云消息传递的 Vue pwa 无法正常工作