Pinia state
访问
state
,允许直接修改值的<template> <div> pinia:{{ Test.current }} <button @click="change">change</button> </div> </template> <script setup lang="ts"> import {useTestStore} from "./store"; const Test = useTestStore() const change = () => { Test.current++ } </script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15改变状态,调用
$patch
方法,批量修改多个值<template> <div> pinia:{{ Test.current }} <button @click="change">change</button> </div> </template> <script setup lang="ts"> import {useTestStore} from "./store"; const Test = useTestStore() const change = () => { Test.$patch({ current: 888 }) } </script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17批量修改函数形式(推荐使用函数形式 可以自定义修改逻辑)。
任何集合修改(例如,从数组中推送、删除、拼接元素)都需要您创建一个新集合。
<template> <div> <button @click="Add">+</button> <div> {{Test.current}} </div> <div> {{Test.age}} </div> </div> </template> <script setup lang='ts'> import {useTestStore} from './store' const Test = useTestStore() const Add = () => { Test.$patch((state)=>{ state.current++; state.age = 40 }) } </script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23通过原始对象修改整个实例
$state
您可以通过将store
的属性设置为新对象来替换store
的整个状态缺点就是必须修改整个对象的所有属性
<template> <div> <button @click="Add">+</button> <div> {{Test.current}} </div> <div> {{Test.age}} </div> </div> </template> <script setup lang='ts'> import {useTestStore} from './store' const Test = useTestStore() const Add = () => { Test.$state = { current:10, age:30 } } </script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22通过
actions
修改。定义actions
在actions
中直接使用this
就可以指到state
里面的值// store/index.ts import { defineStore } from 'pinia' import { Names } from './store-name' export const useTestStore = defineStore(Names.TEST, { state:()=>{ return { current:1, age:30 } }, actions:{ setCurrent (num:number) { this.current = num } } }) // 使用方法直接在实例调用 <template> <div> <button @click="Add">+</button> <div> {{Test.current}} </div> <div> {{Test.age}} </div> </div> </template> <script setup lang='ts'> import {useTestStore} from './store' const Test = useTestStore() const Add = () => { Test.setCurrent(333) } </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
28
29
30
31
32
33
34
35
36
37
上次更新: 2024/08/14, 04:14:33