一、安装 Pinia 的步骤
1、安装 Pinia
npm install pinia
2、在 Vue 应用中引入 Pinia
在 main.js
中引入并注册 Pinia:
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';
const app = createApp(App);
app.use(createPinia()); // 注册 Pinia
app.mount('#app');
二、使用Pinia
1、创建 Store 文件
手动创建 stores
目录和具体的 Store 文件,例如 src/stores/counter.js
:
// src/stores/counter.js
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
}),
getters: {
doubleCount: (state) => state.count * 2,
},
actions: {
increment() {
this.count++;
},
},
});
2、在组件中使用 Store
在组件中引入并使用 Store:
<template>
<div>
<p>Count: {{ count }}</p>
<p>Double Count: {{ doubleCount }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script setup>
import { useCounterStore } from '@/stores/counter';
import { storeToRefs } from 'pinia';
const counterStore = useCounterStore();
const { count, doubleCount } = storeToRefs(counterStore);
const { increment } = counterStore;
</script>
三、如何组织 Store 文件
你可以根据项目的复杂度来组织 Store 文件,例如:
单一文件:将所有状态放在一个 Store 文件中(适合小型项目)。
模块化:将不同的状态拆分到多个 Store 文件中(适合中大型项目)。
例如:
src/
stores/
counter.js
user.js
settings.js
四、实例
1、store写入
用户数据的存储、设置
①写入基本框架
路径:在src/stores/user.js
没有就新建
//引入用到的vue方法和pinia方法
import { reactive, computed } from 'vue'
import { defineStore } from 'pinia'
//定义一个用户Store
export const userStore = defineStore('userinfo', () => {
return { }
})
②申明用户信息,获取用户信息
声明的userinfo是一个对象,所以采用reactive({})去定义
获取用户名和昵称:用户信息内取到的信息都是根据用户信息去计算的,所以需要用到计算属性computed,去取出userinfo内的信息
//声明用户信息
const userinfo = reactive({});//对象
//获取用户名、昵称等。由于用户名是通过用户信息获取的,所以需要一个计算属性
const username = computed(() => userinfo.name);
const nickname = computed(() => userinfo.nickname);
const phone = computed(() => userinfo.phone);
③设置用户信息
使用Object.assign,如果存在新的,就会替换原始的数据
//设值用户信息
const setUserinfo = (info) => {
//对象使用assign,如果userInfo中有相同的key,则info覆盖userInfo的key信息,把之前有的信息进行更换)
Object.assign(userinfo, info)
}
④返回需要用到的数据
return { userinfo, username, nickname, phone ,setUserinfo}
2、引用
①引入方法
import { userStore } from '@/stores/user'
②用法
//读取用户信息
const userstore = userStore();
//获取用户信息中的username
userstore.username
//将用户信息设置到store中
userstore.setUserinfo(res.data)