import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
const pinia = createPinia()
const app = createApp(App)
app.use(pinia)
app.mount('#app')
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
name: 'Counter'
}),
getters: {
doubleCount: (state) => state.count * 2,
doublePlusOne() {
return this.doubleCount + 1
}
},
actions: {
increment() {
this.count++
},
async fetchData() {
const response = await fetch('/api/data')
this.count = await response.json()
}
}
})
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const name = ref('Counter')
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
}
return { count, name, doubleCount, increment }
})
<script setup>
import { useCounterStore } from '@/stores/counter'
const counter = useCounterStore()
console.log(counter.count)
console.log(counter.doubleCount)
counter.increment()
</script>
<template>
<div>{{ counter.count }}</div>
<button @click="counter.increment">+1</button>
</template>
<script setup>
import { storeToRefs } from 'pinia'
import { useCounterStore } from '@/stores/counter'
const counter = useCounterStore()
const { count, doubleCount } = storeToRefs(counter)
const { increment } = counter
</script>
const counter = useCounterStore()
console.log(counter.count)
counter.count++
counter.$patch({
count: counter.count + 1,
name: 'New Name'
})
counter.$patch((state) => {
state.count++
state.items.push({ name: 'shoes' })
})
counter.$state = { count: 0, name: 'Counter' }
export const useStore = defineStore('main', {
state: () => ({
count: 0
}),
getters: {
doubleCount(state) {
return state.count * 2
},
doublePlusOne() {
return this.doubleCount + 1
},
getUserById: (state) => {
return (userId) => state.users.find((user) => user.id === userId)
}
}
})
export const useStore = defineStore('main', {
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++
},
async fetchData() {
try {
const response = await fetch('/api/data')
this.count = await response.json()
} catch (error) {
console.error(error)
}
}
}
})
const counter = useCounterStore()
counter.$subscribe((mutation, state) => {
console.log(mutation.type)
console.log(mutation.storeId)
console.log(state)
})
counter.$onAction(({
name,
store,
args,
after,
onError
}) => {
console.log(`Action ${name} called`)
after((result) => {
console.log('Action finished')
})
onError((error) => {
console.error('Action failed')
})
})
export function myPiniaPlugin(context) {
context.pinia
context.app
context.store
context.options
return {
secret: 'the cake is a lie'
}
}
const pinia = createPinia()
pinia.use(myPiniaPlugin)