Actions

同步直接调用即可。/store/index.ts:

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
import { defineStore } from "pinia"
import { Names } from "./store-name"

type User = {
name: string,
age: number
}

let result:User = {
name: "yjsp",
age: 24
}

export const useTestStore = defineStore(Names.TEST, {
state: () => ({
user: <User>{},
name: "yajue"
}),

actions: {
setUser() {
this.user = result
}
}
})

异步使用async/await即可。/store/index.ts:

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
import { defineStore } from "pinia"
import { Names } from "./store-name"

type User = {
name: string,
age: number
}

const Login = (): Promise<User> => {
return new Promise((resolve,reject)=> {
setTimeout(() => {
resolve({
name: "yjsp",
age: 24
})
}, 2000)
})
}

export const useTestStore = defineStore(Names.TEST, {
state: () => ({
user: <User>{},
name: "yajue"
}),

actions: {
async setUser() {
const result = await Login()
this.user = result
// action中的方法可以相互调用
this.setName(this.user.name)
},
setName(name:string) {
this.name = name
}
}
})

App.vue:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<template>
<div>
actions: {{ Test.user }} --- {{ Test.name }}
<br>
<button @click="change">change</button>
</div>
</template>

<script setup lang="ts">
import { useTestStore } from "./store"

const Test = useTestStore()

const change = ()=> {
Test.setUser()
}
</script>

Getters

/store/index.ts:

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
import { defineStore } from "pinia"
import { Names } from "./store-name"

type User = {
name: string,
age: number
}

const Login = (): Promise<User> => {
return new Promise((resolve,reject)=> {
setTimeout(() => {
resolve({
name: "yjsp",
age: 24
})
}, 2000)
})
}

export const useTestStore = defineStore(Names.TEST, {
state: () => ({
user: <User>{},
name: "yajue"
}),

getters: {
newName():string {
// getters中的方法可以相互调用
return `***${this.name} - ${this.getUserAge}***`
},
getUserAge(): number {
return this.user.age
}
},
})

App.vue:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<template>
<div>
getters: {{ Test.newName }}
<br>
<button @click="change">change</button>
</div>
</template>

<script setup lang="ts">
import { useTestStore } from "./store"

const Test = useTestStore()

const change = ()=> {
Test.setUser()
}
</script>