To automatically import Pinia stores in Nuxt, you can do the following:
Install the @nuxtjs/composition-api
module by running the following command:
npm install @nuxtjs/composition-api
In your nuxt.config.js
file, add the following configuration:
export default {
// ...
buildModules: [
'@nuxtjs/composition-api/module',
],
plugins: [
{ src: '~/plugins/pinia.js', mode: 'client' },
],
// ...
}
This configuration tells Nuxt to use the @nuxtjs/composition-api
module and to load a client-side plugin for Pinia.
Create a plugins/pinia.js
file in your project with the following contents:
import { createPinia } from 'pinia'
export default ({ app }) => {
// Create a new Pinia instance
const pinia = createPinia()
// Make the Pinia instance available in the Nuxt app
app.use(pinia)
}
This file creates a new Pinia instance and makes it available in the Nuxt app.
Create your Pinia stores in the store
directory of your project. For example, you could create a todos.js
store with the following contents:
import { defineStore } from 'pinia'
export const useTodosStore = defineStore({
id: 'todos',
state: () => ({
todos: [],
}),
actions: {
async fetchTodos() {
const todos = await fetch('/todos').then(res => res.json())
this.todos = todos
},
},
})
This file defines a Pinia store for managing a list of todos.
In your pages or components, import and use your Pinia stores using the useStore
function from Pinia:
<template>
<div v-for="todo in todos" :key="todo.id">{{ todo.title }}</div>
</template>
<script>
import { useStore } from 'pinia'
import { useTodosStore } from '~/store/todos'
export default {
async fetch() {
const store = useStore()
await store.fetchTodos()
},
setup() {
const store = useTodosStore()
return {
todos: store.todos,
}
},
}
</script>
This example fetches the todos from an API in the fetch
hook and displays them in the template using the todos
property from the Pinia store.
Asked: 2023-07-09 01:17:08 +0000
Seen: 11 times
Last updated: Jul 09 '23