官网

npm install pinia@latest
yarn add pinia

配置

1
2
3
4
//main.js
import { createPinia } from 'pinia'
const pinia = createPinia()
app.use(pinia)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//store.js
import {defineStore} from 'pinia'
export const mainStore = defineStore('main',{
state:()=>{
return {
message:'hello world!'
}
},
getters:{

},
actions:{

}
})

vue模版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{{store.message}}
<script setup>
import {mainStore} from '../store/store.js'
const store = mainStore()
</script>
//or
<script>
import {mainStore} from '../store/store.js'
export default{
setup(){
const store = mainStore()
return {}
}
}
</script>

方法改变变量值

1
2
3
4
5
6
7
8
<script setup>
import { mainStore } from '../store/index'
const store = mainStore()
const countFun = ()=>{
store.count++
}
</script>
<button type="button" @click="countFun()">count is: {{ store.count }}</button>

解构方法有坑 只能调用默认数据 需要用pinia方法storeToRefs

1
2
3
4
5
6
7
8
9
10
{{count}}
<script setup>
//错误方法
const {count} = store

//正确方法
import {storeToRefs} from 'pinia'
const {count} = storeToRefs(store)

</script>

四种修改状态数据的方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//1.
const countFunc=()=>{
store.count++
}
//2.利于多数据修改(经过优化的)
const countFunc2=()=>{
store.$patch({
count:store.count+2,
message:'abc'
})
}
//3.处理复杂过程实用
const countFunc3=()=>{
store.$patch((state)=>{
state.count++;
})
}
//4.卸载actions中 不能用箭头函数
//store.js
actions:{
change(){
this.count ==;
}
}
//调用
<button type="button" @click="store.change()">count is: {{ store.count }}</button>

1
2
3
4
5
6
7
8
9
10
11
getters:{
phoneMask(){
return this.phone.toString().replace(/^(\d{3})\d{4}(\d{4})$/,'$1****$2')
}
},

getters:{
phoneMask(state){
return state.phone.toString().replace(/^(\d{3})\d{4}(\d{4})$/,'$1****$2')
}
},

仓库之间调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//other.js
import { defineStore } from "pinia";
export const otherStore = defineStore('other',{
state:()=>{
return {
list:[1,2,3]
}
}
})
//store.js
import { otherStore } from './other'
actions:{
getList(){
console.log(otherStore().list)
}
}
//模版页
store.getList()

vue2.+

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//mian.js
import { createPinia, PiniaVuePlugin } from 'pinia'
Vue.use(PiniaVuePlugin)
const pinia = createPinia()

new Vue({
router,
pinia,
render: h => h(App)
}).$mount('#app')
//store.js
import { defineStore } from 'pinia'
export const mainStore = defineStore('counter', {
state: () => ({
personName:'',
loadingState:false
}),
getters: {
//double: state => state.count * 2,
},
actions: {
increment() {
//this.count++
},
},
})
//components.vue
import { mainStore } from '@/store/index'
data(){
return {
store:'',
}
},
mounted(){
this.store = mainStore()
},
methods:{
bindSubmit(){
this.store.loadingState = true
}
}