Pinia 简介
Pinia 是一个状态管理库,用于 Vue.js 应用程序中的集中式状态管理。与 Vuex 不同的是,Pinia 基于 Vue 3 的新响应式 API,具有更好的类型安全和 TypeScript 支持,同时也更加轻量级。
Pinia 的使用方法
安装 Pinia
在使用 Pinia 之前,您需要先安装它。可以使用 NPM 或 Yarn 进行安装:
npm install pinia --save
或者
yarn add pinia
创建 Store
与 Vuex 类似,Pinia 中心是一个 store,它包含应用程序中的所有状态。创建一个 store 非常简单,只需传入一个对象:
import { createPinia } from 'pinia';
const pinia = createPinia();
pinia.store({
id: 'myStore',
state: () => ({
count: 0,
}),
});
以上代码创建了一个名为 myStore
的 Pinia 实例,其中包含一个 state
对象,该对象包含一个 count
属性并将其初始化为 0。
获取状态
您可以通过在组件中调用 $store.$state
来获取状态:
import { defineComponent } from 'vue';
import { useStore } from 'pinia';
export default defineComponent({
name: 'MyComponent',
setup() {
const store = useStore('myStore');
return {
count: store.$state.count,
};
},
});
更改状态
更改 Pinia 中的状态是非常简单的。您只需要在 store 实例中调用 mutations,即定义一些函数来修改状态。
pinia.store({
id: 'myStore',
state: () => ({
count: 0,
}),
actions: {
increment() {
this.count++;
},
},
});
在以上示例中,我们定义了一个名为 increment
的 mutation,该函数将 count
状态增加 1。
您可以在组件中提交 mutation,以更改状态:
import { defineComponent } from 'vue';
import { useStore } from 'pinia';
export default defineComponent({
name: 'MyComponent',
setup() {
const store = useStore('myStore');
function handleClick() {
store.increment();
}
return {
handleClick,
};
},
});
使用 Getters
Getters 允许您从 store 中获取派生状态。
pinia.store({
id: 'myStore',
state: () => ({
count: 0,
}),
getters: {
double(state) {
return state.count * 2;
},
},
});
在以上示例中,我们定义了一个名为 double
的 getter,它返回 count
状态的两倍。
您可以在组件中使用 getter,以获取派生状态:
import { defineComponent } from 'vue';
import { useStore } from 'pinia';
export default defineComponent({
name: 'MyComponent',
setup() {
const store = useStore('myStore');
const double = store.double;
return {
double,
};
},
});
结论
Pinia 是一个用于 Vue.js 应用程序的轻量级状态管理库,它采用了 Vue 3 的新响应式 API,并具有更好的类型安全和 TypeScript 支持。它提供了一个集中式的状态管理方案,使组件之间更容易共享数据,并允许您以预测和可维护的方式更改状态。