温馨提示:本文以vue3+vite+ts举例,vite配置和ts语法侧重较少,比较适合有vuex或者vue基础的小伙伴们儿查阅.
yarn add pinia
npm install pinia
pnpm add pinia
main.ts
中直接引入pinia 在 src/main.ts 中引入pinia(根存储),并传递给应用程序.
import { createApp } from 'vue' import './style.css' import App from './App.vue' // 1-创建一个 pinia(根存储) import { createPinia } from 'pinia' const app = createApp(App) // 2-告诉应用程序,我们将使用pinia const pinia = createPinia(); // 以插件形式传递给app app.use(pinia); app.mount('#app');
.ts
文件引入pinia 在根目录下新建文件夹,这里我命名为 store ,再在文件夹下新建一个 index.ts 文件( src/store/index.ts ),用以配置和引入pinia.
// 1-创建一个 pinia(根存储) import { createPinia } from 'pinia' // 2-定义pinia实例 const pinia = createPinia(); // 3-暴露pinia实例 export default pinia;
然后在 src/main.ts 中使用.
...... import pinia from '@/store/index.ts' app.use(pinia); ......
其实和方式一没啥区别,只是为了保持 main.ts 文件整洁,并且方便配置pinia.
pinia与vuex差不多,相比于vuex,少了 mutation 和 modules .
pinia创建仓库,有 选项式写法 和 组合式写法 .
在根目录下创建一个文件夹store ( src/store ),在store文件夹中可以创建你的仓库,比如下面我创建了一个名为user的仓库 ( src/store/user.ts ).
// 选项式写法 // 1-引入api import { defineStore } from "pinia"; // 2-定义仓库 const store = defineStore('user', { // 3-设置组件共享的状态,相当于组件的data state: () => ({ userInfo: { name: '老刘', sex: '男', age: 17, isStudent: false }, token: '5201314', password: '123456', }), // 3-设置状态计算值,相当于组件的computed getters: { name: (state) => state.userInfo.name, sex: (state) => state.userInfo.sex, }, // 3-设置组件共享的方法,相当于组件的methods actions: { addAge() { this.userInfo.age++; } } }); // 最后别忘了把仓库暴露出去哦 export default store;
上面的仓库 ( src/store/user.ts )组合式写法如下:
// 组合式写法 // 1-引入pinia的api import { defineStore } from "pinia"; // 2-引入vue3相关api import { ref, reactive, computed } from 'vue'; // 3-定义仓库,注意第二个参数需要传入一个函数,函数需要返回一个对象! const store = defineStore('user', () => { // 4-在这里面可以像在组件中一样,使用vue3的API,定义响应式数据 const userInfo = reactive({ name: '老刘', sex: '男', age: 17, isStudent: false }); const token = ref('5201314'); const password = ref('123456'); // 这里computed的作用相当于getters const name = computed(() => userInfo.name); const sex = computed(() => userInfo.sex); // 4-还可以定义方法 function addAge() { userInfo.age++; } // 5-然后把需要共享的数据或方法,装进一个对象,return出去 return { userInfo, token, password, name, sex, addAge } }); // 最后别忘了把仓库暴露出去哦 export default store;
TIP 。
还可以在仓库中使用 watch 、 watchEffect 等vue3的API喔~.
import { ref, reactive, computed, watch } from 'vue'; const store = defineStore('user', () => { const userInfo = reactive({ age: 17, }); // 使用vue3的watch()函数,可以对仓库状态进行监听 watch(() => userInfo.age, (val) => { console.log(val); }); });
完成了上面的工作后,我们就可以在组件中愉快地使用pinia啦! 。
下面以 src/App.vue 作为示例.
state
Và getters
在模板和script中,state和getters可以看作仓库实例(如 userStore )的属性,直接加 . 访问即可.
姓名:{{ userStore.name }} 性别:{{ userStore.sex }} 年龄:{{ userStore.userInfo.age }} 是否学生:{{ userStore.userInfo.isStudent ? '是' : '否' }}
userStore Proxy(Object) {$id: 'user', $onAction: ƒ, $patch: ƒ, $reset: ƒ, $subscribe: ƒ, …}[[Handler]]: Object[[Target]]: Object[[IsRevoked]]: false 姓名: 老刘 性别: 男 年龄: 17 是否学生: 否
actions
使用仓库方法与访问仓库state类似,仓库实例后直接加 . 调用即可.
年龄:{{ userStore.userInfo.age }}
state
与vuex不同,pinia支持在组件中直接修改 state .
年龄:{{ userStore.userInfo.age }}
actions
进行修改 src/store/user.ts 。
...... const store = defineStore('user', () => { ...... // 1-定义方法 function addAge() { userInfo.age++; } // 2-return出去 return { addAge } }); // 3-导出仓库 export default store;
src/App.vue 。
年龄:{{ userStore.userInfo.age }}
通过仓库实例(如 userStore )的 $patch 方法,可以对 state 同时应用多个更改.
上面的方法每次进行批量修改都需要传入一个新对象,有时候使用起来并不方便。下面是另一种写法, $patch 接受一个函数来批量修改集合内部分对象。(推荐) 。
通过仓库实例(如 userStore )的 $state 属性 ,来为新对象 替换 仓库的整个状态.
pinia官网提到整体替换state的方法,但并未说明是否保留数据响应式。经笔者实践,这种方法 会丢失数据的响应式 ,所以 不推荐使用 .
state
通过调用仓库实例上的 $reset() 方法将状态 重置 到其初始值.
$reset()
的坑 细心的你会发现,仓库 state 并没有重置,然后你打开你的的控制台,你会惊讶地发现它报了这么一个错误:
这时候请你不要慌,先冷静地看一下报错信息.
这里翻译一下: Store "user"是使用setup语法构建的,不实现$reset() 。(猜测是pinia的缺陷) 。
所以,根据报错信息,这里提供下面两种解决方案.
使用 选项式Options API编写pinia仓库 ,并且 在组件中不能用script setup语法,要使用setup函数进行开发.
src/store/user.ts 。
...... // 使用选项式Options API编写仓库 const store = defineStore('user', { // 3-设置组件共享的状态,相当于组件的data state: () => ({ userInfo: { name: '老刘', sex: '男', age: 17, isStudent: false }, token: '5201314', password: '123456', }), }); export default store;
src/App.vue 。
$reset()
方法(推荐) 原理:自定义pinia插件(Plugins),利用 $patch() 重置整个 state .
在之前创建的pinia配置文件中修改( src/store/index.ts ).
import { createPinia } from 'pinia'; const pinia = createPinia(); // 1-使用pinia自定义插件 pinia.use(({ store }) => { // 2-获取最开始的State const initialState = JSON.parse(JSON.stringify(store.$state)); // 3-重写$reset()方法 store.$reset = () => { // 4-利用$patch()批量变更state,达到重置state的目的 store.$patch(initialState); } }); export default pinia;
推荐使用这种方法,这样就可以在 script setup 中愉快地使用pinia啦! 。
src/store/index.ts 。
import { createPinia } from 'pinia'; const pinia = createPinia(); pinia.use(({ store }) => { const initialState = JSON.parse(JSON.stringify(store.$state)); store.$reset = () => { store.$patch(initialState); } }); export default pinia;
src/store/user.ts 。
// 组合式写法 import { defineStore } from "pinia"; import { ref, reactive, computed, watch } from 'vue'; const store = defineStore('user', () => { const userInfo = reactive({ name: '老刘', sex: '男', age: 17, isStudent: false }); const token = ref('5201314'); const password = ref('123456'); const name = computed(() => userInfo.name); const sex = computed(() => userInfo.sex); watch(() => userInfo.age, (val) => { console.log(val); }); function addAge() { userInfo.age++; } return { userInfo, token, password, name, sex, addAge } }); export default store;
src/App.vue 。
Tôi là thành phần chính
src/components/sonA.vue 。
Tôi là thành phần phụ A
Tên: {{ userStore .name } Giới tính: {{ userStore.sex } Tuổi: {{ userStore.userInfo.age } Là học sinh: {{ userStore.userInfo.isStudent ? 'Có' : 'Không' }