import { defineStore } from 'pinia'
export const useCounterStore = defineStore({
id: 'counter',
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++
},
decrement() {
this.count--
}
}
})
{{ counter.count }}
import { defineStore } from 'pinia'
export const useCounterStore = defineStore({
id: 'counter',
state: () => ({
count: 0
}),
getters: {
isPositive() {
return this.count > 0
}
},
actions: {
increment() {
this.count++
},
decrement() {
this.count--
}
}
})
import { defineStore } from 'pinia'
import { useCounterStore } from './counter'
export const useUserStore = defineStore({
id: 'user',
state: () => ({
name: 'test',
age: 20
}),
getters: {
message() {
return `${useCounterStore().count} ${this.name} ${this.age}`
}
}
})
import { createPinia } from 'pinia'
import { useCounterStore } from './store'
const app = createApp(App)
app.use(createPinia())
app.provide('counterStore', useCounterStore())
app.mount('#app')
import { useCounterStore } from './store'
useCounterStore().increment()
import { defineStore } from 'pinia'
export const useUserStore = defineStore({
id: 'user',
state: () => ({
name: localStorage.getItem('name') || '',
age: localStorage.getItem('age') || ''
}),
actions: {
setName(name) {
this.name = name
localStorage.setItem('name', name)
},
setAge(age) {
this.age = age
localStorage.setItem('age', age)
}
}
})
import { defineStore } from 'pinia'
export const useUserStore = defineStore({
id: 'user',
state: () => ({
name: '',
age: ''
}),
actions: {
async fetchData() {
const data = await fetch('https://api.example.com/user')
const { name, age } = await data.json()
this.name = name
this.age = age
}
}
})
import { defineStore } from 'pinia'
export const useUserStore = defineStore({
id: 'user',
state: () => ({
name: '',
age: ''
}),
mutations: {
setName(name) {
this.name = name
},
setAge(age) {
this.age = age
}
},
actions: {
fetchData() {
fetch('https://api.example.com/user')
.then((data) => data.json())
.then(({ name, age }) => {
this.setName(name)
this.setAge(age)
})
}
}
})
import { createPinia } from 'pinia'
import { useCounterStore } from './store'
function myPlugin(pinia) {
pinia.use((context) => {
context.$counter = useCounterStore()
})
}
const app = createApp(App)
app.use(createPinia())
app.use(myPlugin)
app.mount('#app')