pinia (3) 建立 actions

建立 actions

我們可以建立 actions 來更新 state 裡的資料。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
}),
actions: {
// since we rely on `this`, we cannot use an arrow function
increment() {
this.count++
},
randomizeCounter() {
this.count = Math.round(100 * Math.random())
},
},
})

在元件裡使用 actions

1
2
3
4
5
6
7
8
9
10
<script setup>
const store = useCounterStore()
// call the action as a method of the store
store.randomizeCounter()
</script>

<template>
<!-- Even on the template -->
<button @click="store.randomizeCounter()">Randomize</button>
</template>

非同步使用

actions 裡也可執行非同步執行程式,如打api或取資料後再更新state。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { mande } from 'mande'

const api = mande('/api/users')

export const useUsers = defineStore('users', {
state: () => ({
userData: null,
// ...
}),

actions: {
async registerUser(login, password) {
try {
this.userData = await api.post({ login, password })
showTooltip(`Welcome back ${this.userData.name}!`)
} catch (error) {
showTooltip(error)
// let the form component display the error
return error
}
},
},
})