Pinia官网地址
Pinia的优势
Pinia是一个全新的Vue状态管理库,是Vuex的代替者,尤雨溪强势推荐
- Vue2 和 Vue3 都能支持
- 抛弃传统的 Mutation ,只有 state, getter 和 action ,简化状态管理库
- 不需要嵌套模块,符合 Vue3 的 Composition api,让代码扁平化
- TypeScript支持
- 代码简洁,很好的代码自动分割
Pinia的基本使用
初始化项目
npm init vite@latest
安装
npm install pinia
yarn add pinia
挂载Pinia
// src/main.ts
import { createPinia } from 'pinia'
const pinia = createPinia()
createApp(App).use(pinia).mount('#app')
创建store
// src/store/index.ts
import { defineStore } from "pinia";
export const mainStore = defineStore("main", {
state: () => {
return {
msg: "hello world",
};
},
getters: {},
actions: {},
});
注:这是官网上提供的常规写法,我个人还是更偏向于下面这种写法:
// src/store/index.ts
import { defineStore } from "pinia";
interface State {
msg: string;
count: number;
}
const defaultState:State = {
msg: "hello world!"
}
export const mainStore = defineStore("main", {
state: () => {
return defaultState;
},
getters: {},
actions: {},
},
});
使用Store
// src/components/HelloWorld.vue
<script setup lang="ts">
import { mainStore } from '../store';
const store = mainStore()
</script>
<template>
<h1>{
{store.msg}}</h1>
</template>
<style scoped>
</style>
解构store
当store中的多个参数需要被使用到的时候,为了更简洁的使用这些变量,我们通常采用结构的方式一次性获取所有的变量名
- ES传统方式解构(能获取到值,但是不具有响应性)
// src/components/HelloWorld.vue
<script setup lang="ts">
import { mainSt