What is @pinia/nuxt?
@pinia/nuxt is a package that integrates Pinia, a state management library, with Nuxt.js, a framework for creating Vue.js applications. This package allows you to manage the state of your application in a more structured and maintainable way, leveraging the capabilities of both Pinia and Nuxt.js.
What are @pinia/nuxt's main functionalities?
State Management
This feature allows you to define a store with state and actions. In this example, a counter store is defined with a state property 'count' and an action 'increment' to modify the state.
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++;
}
}
});
Nuxt Integration
This feature demonstrates how to integrate Pinia with a Nuxt.js project. The configuration includes the @pinia/nuxt module and sets up auto-imports for commonly used Pinia functions.
export default defineNuxtConfig({
modules: [
'@pinia/nuxt',
],
pinia: {
autoImports: [
'defineStore',
'storeToRefs',
],
},
});
Using Stores in Components
This feature shows how to use a Pinia store within a Nuxt.js component. The counter store is imported and used to display and modify the count state.
<template>
<div>
<p>{{ count }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script setup>
import { useCounterStore } from '~/stores/counter';
const counterStore = useCounterStore();
const { count } = storeToRefs(counterStore);
const { increment } = counterStore;
</script>
Other packages similar to @pinia/nuxt
vuex
Vuex is a state management library for Vue.js applications. It is similar to Pinia in that it provides a centralized store for all the components in an application. However, Vuex has a more complex API and is more opinionated compared to Pinia, which is simpler and more flexible.
redux
Redux is a state management library commonly used with React, but it can also be used with Vue.js. It provides a predictable state container and is known for its strict unidirectional data flow. Compared to Pinia, Redux has a steeper learning curve and requires more boilerplate code.
mobx
MobX is a state management library that makes state management simple and scalable by transparently applying functional reactive programming. It can be used with Vue.js and offers a more flexible and less opinionated approach compared to Vuex and Redux.
@pinia/nuxt
Nuxt 2 & 3 module
Installation
npm i pinia @pinia/nuxt
Usage
Add to modules
(Nuxt 3) or buildModules
(Nuxt 2) in nuxt.config.js
:
export default {
buildModules: [['@pinia/nuxt', { disableVuex: true }]],
}
export default defineNuxtConfig({
modules: ['@pinia/nuxt'],
})
Note you also need @nuxtjs/composition-api
if you are using Nuxt 2 without Bridge. Refer to docs for more.
License
MIT