What tools are used to store global state in Vue.js? What is the difference between Options API and Composition API in Pinia?
sobes.tech AI
Answer from AI
To store global state in Vue.js, tools like Vuex and Pinia are often used. Vuex was the standard for Vue 2, while Pinia is a more modern and lightweight alternative recommended for Vue 3.
Pinia supports two main ways to define a store: Options API and Composition API.
-
Options API in Pinia resembles the Vue 2 syntax, where state, getters, and actions are described as objects and methods. This is convenient for those accustomed to the traditional Vue style.
-
Composition API uses functions and reactive variables, offering greater flexibility and better integration with modern Vue 3. Here, state is created using
reforreactive, and functions are returned from the store.
Example of Pinia with Composition API:
import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
function increment() {
count.value++
}
return { count, increment }
})
Example of Pinia with Options API:
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
actions: {
increment() {
this.count++
}
}
})
The main difference lies in style and approach to reactivity: Composition API is more declarative and flexible, while Options API is simpler for beginners and more familiar.