How can I fetch data in a Nuxt 3 app when the app starts and persist that data?

huangapple go评论75阅读模式
英文:

How can I fetch data in a Nuxt 3 app when the app starts and persist that data?

问题

在Nuxt 2中,我在Vuex存储的索引文件中使用nuxtServerInit()方法来触发一个存储操作,从API获取数据并将其提交到存储中。

在Nuxt 3中,我该如何实现相同的功能?

目前,我已经安装了Pinia,并设置了一个简单的存储:

import { defineStore } from 'pinia';

export const usePersonalisationStore = defineStore({

  id: 'personalisation-store',

  state: () => {
    return {
      data: null,
    }
  },

  actions: {

    async setData (id) {

      if (!id) return

      this.data = {
        'someApp': {
          id: id
        }
      }

    }
  },

  getters: {
    practiceData: state => state.data,
  },

})

以及以下插件personalisation.server.js

import { usePersonalisationStore } from "~/store/personalisation";

export default defineNuxtPlugin((nuxtApp) => {

  const store = usePersonalisationStore()
  const route = useRoute()
  const { setData } = store

  setData(route.query.id)

})

这只是查看路由查询字符串并更新存储。我想在这里执行一个异步API调用来获取数据,然后使用这些数据更新存储。

英文:

In Nuxt 2, I used the nuxtServerInit() method within the Vuex store's index file to dispatch a store action that retrieved data from an API and committed to that to the store.

How can I achieve the same in Nuxt 3?

At present I have pinia installed with a simple store set up:

import { defineStore } from 'pinia'

export const usePersonalisationStore = defineStore({

  id: 'personalisation-store',

  state: () => {
    return {
      data: null,
    }
  },

  actions: {

    async setData (id) {

      if ( ! id) return

      this.data = {
        'someApp': {
          id: id
        }
      }

    }
  },

  getters: {
    practiceData: state => state.data,
  },

})

And the following plugin personalisation.server.js:

import { usePersonalisationStore } from "~/store/personalisation";

export default defineNuxtPlugin((nuxtApp) => {

  const store = usePersonalisationStore()
  const route = useRoute()
  const { setData } = store

  setData(route.query.id)

})

This just looks at the route querystring and updates the store. What I want to do here is make an asynchronous API call to fetch data, and then update the store with the data.

答案1

得分: 1

以下是您要翻译的代码部分:

> "This just looks at the route querystring and updates the store. What I want to do here is make an asynchronous API call to fetch data, and then update the store with the data."

这只是查看路由查询字符串并更新存储。我想在这里进行异步API调用以获取数据,然后使用该数据更新存储。

It is not apparent what you're trying to do there but I'll give it a shot.

不清楚您在尝试做什么,但我会尝试解释。

If what you are wanting to do is have a plugin to fetch data, you will need to provide a helper for the NuxtApp to use the data from your plugin:

如果您想要创建一个插件来获取数据,您需要为NuxtApp提供一个辅助函数,以便从您的插件中使用数据:

export default defineNuxtPlugin(() => {
  // 在此处获取数据
  return {
    provide: {
      fetchedData: data
    }
  }
})

As stated in https://nuxt.com/docs/guide/directory-structure/plugins

https://nuxt.com/docs/guide/directory-structure/plugins中所述

Otherwise, if you're just trying to fetch data when the app is created, and persist it in the pinia state, you can just use the setup hook inside your app.vue. If you don't have an app.vue, just create it in your root directory, and Nuxt will use its directives to override the default Vue app that is instantiated by Nuxt.

否则,如果您只是想在创建应用程序时获取数据,并将其保存在pinia状态中,您可以在app.vue中使用setup钩子。如果您没有app.vue,请在根目录中创建它,Nuxt将使用其指令来覆盖Nuxt实例化的默认Vue应用程序。

In app.vue

在app.vue中

<template>
    <!-- 您的应用程序 -->
<template/>
<script setup>
    import { usePersonalisationStore } from "~/store/personalisation"
    <!-- 在此处从pinia中获取数据 -->
    const store = usePersonalisationStore();
    await store.fetchData()
    <!-- 数据现在已设置并可用 -->
    const fetchedData = computed(() => { return store.getFetchedData });
</script>

And in the ~/store/personalisation.js

并在~/store/personalisation.js中

import { defineStore } from 'pinia'

export const usePersonalisationStore = defineStore({

  id: 'personalisation-store',

  state: () => {
    return {
      data: null,
      fetchedData: null
    }
  },

  actions: {

    async setData (id) {

      if ( ! id) return

      this.data = {
        'someApp': {
          id: id
        }
      }

    },
    async fetchData() {
        const data = await useFetch('URI');
        this.fetchedData = data;
    }
  },

  getters: {
    practiceData: state => state.data,
    getFetchedData() { return this.fetchedData }
  },

})

These concepts are documented in https://nuxt.com/docs/getting-started/data-fetching, https://nuxt.com/docs/migration/pages-and-layouts#appvue, and https://pinia.vuejs.org/core-concepts/state.html

这些概念在https://nuxt.com/docs/getting-started/data-fetching,https://nuxt.com/docs/migration/pages-and-layouts#appvue和https://pinia.vuejs.org/core-concepts/state.html中有文档记录。

英文:

> "This just looks at the route querystring and updates the store. What I want to do here is make an asynchronous API call to fetch data, and then update the store with the data."

It is not apparent what you're trying to do there but I'll give it a shot.

If what you are wanting to do is have a plugin to fetch data, you will need to provide a helper for the NuxtApp to use the data from your plugin:

export default defineNuxtPlugin(() => {
  // fetch data here
  return {
    provide: {
      fetchedData: data
    }
  }
})

As stated in https://nuxt.com/docs/guide/directory-structure/plugins

Otherwise, if you're just trying to fetch data when the app is created, and persist it in the pinia state, you can just use the setup hook inside your app.vue. If you don't have an app.vue, just create it in your root directory, and Nuxt will use its directives to override the default Vue app that is instantiated by Nuxt.

In app.vue

<template>
    <!-- your app -->
<template/>
<script setup>
    import { usePersonalisationStore } from "~/store/personalisation";
    <!-- await fetch data here from pinia -->
    const store = usePersonalisationStore();
    await store.fetchData()
    <!-- data is now set and usable -->
    const fetchedData = computed(() => { return store.getFetchedData });
</script>

And in the ~/store/personalisation.js

import { defineStore } from 'pinia'

export const usePersonalisationStore = defineStore({

  id: 'personalisation-store',

  state: () => {
    return {
      data: null,
      fetchedData: null
    }
  },

  actions: {

    async setData (id) {

      if ( ! id) return

      this.data = {
        'someApp': {
          id: id
        }
      }

    },
    async fetchData() {
        const data = await useFetch('URI');
        this.fetchedData = data;
    }
  },

  getters: {
    practiceData: state => state.data,
    getFetchedData() { return this.fetchedData }
  },

})

These concepts are documented in https://nuxt.com/docs/getting-started/data-fetching, https://nuxt.com/docs/migration/pages-and-layouts#appvue, and https://pinia.vuejs.org/core-concepts/state.html

答案2

得分: 0

你正在寻找运行时生命周期钩子。你的钩子可能是app:created,因此:

export default defineNuxtPlugin((nuxtApp) => {
    nuxtApp.hook('app:created', () => {
        /* 在此进行数据获取 */
    })
})
英文:

You're looking for Runtime Lifecycle Hooks. Your hook probably would be app:created, so:

export default defineNuxtPlugin((nuxtApp) => {
    nuxtApp.hook('app:created', () => {
        /* data fetching here */
     })
})

huangapple
  • 本文由 发表于 2023年2月23日 20:53:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75545107.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定