Pinia核心概念

Sy_ Lv6

从使用的角度来看基本和Vuex一样,但是更加简单。

有四个常用的核心概念:StateGetterMutationAction。没有了Mutation且常用的只有:StateGettersActions(同步、异步、都支持)。

1.Store

创建一个js/store.js文件:在index.html中使用:
:::: code-tabs
@tab js/store.js

1
2
3
4
5
6
7
8
9
10
const { defineStore } = Pinia; // 引入 defineStore 函数
// 定义一个 id 为 counter 的 Store 实例,最终返回一个调用后可获取该实例的函数,并赋值给 useCounterStore
const useCounterStore = defineStore("counter", {
state: () => ({ // [!code focus:4]
age: 10, // 声明一个状态 age,并赋初始值 10
name: "小蓝", // 声明一个状态 name,并赋初始值“小蓝”
}),
getters: {},
actions: {},
});

@tab index.html

:collapsed-lines
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
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="./lib/vue.min.js"></script>
<script src="./lib/vueDemi.js"></script>
<script src="./lib/pinia.min.js"></script>
<!-- 引入store文件 -->
<script src="./js/store.js"></script>
</head>
<body>
<div id="app">
<h1>姓名: {{ store.name }}</h1>
<h1>年龄: {{ store.age }}</h1>
</div>
<script type="module">
const { createApp } = Vue;
const { createPinia } = Pinia;
const app = Vue.createApp({
// 创建 Vue 实例对象 app
setup() {
const store = useCounterStore(); // 调用 useCounterStore 方法获取 store 对象 counter
return {
store, // 返回 store 对象,方便 DOM 中使用
};
},
});
app.use(createPinia()); // 将 pinia 插件用于 Vue 实例对象 app 中
app.mount("#app");
</script>
</body>
</html>

::::

运行效果:
:::: demo-wrapper no-padding
::: center
20250226235009
:::
::::

2.Getters

Getters可以理解为共享的计算属性,假如需要上面的小蓝的两年后年龄就可以使用Getters

:::: code-tabs
@tab js/store.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const { defineStore } = Pinia;

const useCounterStore = defineStore("counter", {
state: () => ({
age: 10,
name: "小蓝",
}),
getters: { // [!code focus:6]
twoYear: (state) => {
// 定义一个名为 twoYear 的 getter,接收 state 作为第一个参数
return state.age + 2; // 返回基于 state.age 计算后的结果
},
},
actions: {},
});

@tab index.html

1
2
3
4
5
<div id="app">
<h1>姓名: {{ store.name }}</h1>
<h1>年龄: {{ store.age }}</h1>
<h1>两年后年龄为: {{store.twoYear}}</h1> <!-- [!code focus] -->
</div>

::::

3.Actions

如果想要修改原始数据,就需要使用Actions

:::: code-tabs
@tab js/store.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const { defineStore } = Pinia;
const useCounterStore = defineStore("counter", {
state: () => ({
age: 10,
name: "小蓝",
}),
getters: {
twoYear: (state) => {
return state.age + 2;
},
},
actions: { // [!code focus:6]
changeAge() {
// 定义一个函数 changeAge 用于修改 age 的值
this.age++; // 这里的 this 相当于 store.age
},
},
});

@tab index.html

1
2
3
4
5
6
<div id="app">
<h1>姓名: {{ store.name }}</h1>
<h1>年龄: {{ store.age }}</h1>
<h1>两年后年龄为: {{store.twoYear}}</h1>
<button @click="store.changeAge()">年龄+1</button> <!-- [!code focus] -->
</div>

::::

  • 标题: Pinia核心概念
  • 作者: Sy_
  • 创建于 : 2025-06-15 00:51:35
  • 更新于 : 2025-06-15 00:51:35
  • 链接: https://shenying.online//demo/95fgxdcq/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
评论
目录
Pinia核心概念