Pinia全局插件

1、安装pinia

1
npm install pinia -S

2、引入pinia

1
2
3
4
5
6
7
8
import { createPinia } from 'pinia'
import App from './App.vue'

const pinia = createPinia()
const app = createApp(App)

app.use(createPinia())
app.mount('#app')

3、改变pinia

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import {defineStore} from 'pinia'

export const useCounterStore = defineStore({
id: 'counter',
state: () => ({
count: 1,
name: "ksr"
}),
getters: {
},
actions: {
setCurrent(value: any) {
this.count = value
}
},
})

在组件中改变其值的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import {useCounterStore} from './stores/counter'

const counter = useCounterStore()
// 方法一
counter.count++
// 方法二
counter.$patch({current: 2, name: "kss"})
// 方法三
counter.$patch((state) => {
state.current = 2
state.name = "kss"
})
// 方法四
counter.$state = {current: 2, name: "kss"}
// 方法五
counter.setCurrent(2)

pinia 持续化

1
npm install pinia-plugin-persistedstate -S
1
2
3
4
5
6
7
8
9
10
import piniaPersist from 'pinia-plugin-persistedstate'
import { createPinia } from 'pinia'
import App from './App.vue'

const pinia = createPinia()
const app = createApp(App)

pinia.use(piniaPersist)
app.use(pinia)
app.mount('#app')
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import {defineStore} from 'pinia'

export const useCounterStore = defineStore({
id: 'counter',
state: () => ({
count: 1,
name: "ksr"
}),
getters: {
},
actions: {
setCurrent(value: any) {
this.count = value
}
},
persist: true
})