Vue — State
Pinia (recommended)
npm install pinia
// main.js
import { createPinia } from 'pinia'
app.use(createPinia())
Define store
// stores/counter.js
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
getters: {
doubleCount: (state) => state.count * 2
},
actions: {
increment() {
this.count++
}
}
})
Use store
<script setup>
import { useCounterStore } from '@/stores/counter'
const counter = useCounterStore()
</script>
<template>
<p>Count: {{ counter.count }}</p>
<p>Double: {{ counter.doubleCount }}</p>
<button @click="counter.increment()">Add</button>
</template>
Vuex (legacy)
// store/index.js
import { createStore } from 'vuex'
export default createStore({
state: { count: 0 },
mutations: {
increment(state) { state.count++ }
},
actions: {
increment({ commit }) { commit('increment') }
},
getters: {
doubleCount: (state) => state.count * 2
}
})
Use Vuex store
<script>
export default {
computed: {
count() { return this.$store.state.count },
doubleCount() { return this.$store.getters.doubleCount }
},
methods: {
increment() { this.$store.commit('increment') }
}
}
</script>
Pinia vs Vuex
| Feature | Pinia | Vuex |
|---|---|---|
| API | Simpler | Complex |
| TypeScript | Better support | Limited |
| Mutations | None | Required |
| DevTools | Full support | Full support |
Mini Practice
- Create a Pinia store
- Add state, getters, actions
- Use store in components
- Compare with Vuex
Up Next
Continue with API Calls - HTTP requests.
Related Topics
Frequently Asked Questions about State
What is State in Vue?
State is a fundamental concept in Vue. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn State?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn State.
Why is State important in Vue?
State is essential for Vue development. Understanding this concept will help you write better code and solve real-world problems more effectively.