Pinia 的使用

115 阅读2分钟

1. 安装pinia

npm i pinia
// 或者
yarn add pinia

2.创建Store文件

// 在store/index.js文件中
import { createPinia } from 'pinia';
const store = createPinia();
export default store;

3.在main.js 入口文件中集成store

import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
// 对store 的集成
import store from './store';
createApp(App).use(router).use(store).mount('#app');

4.在store文件夹下面可以创建多个片段仓库(模块化)

// 比如创建一个管理用户数据的片段  user.js 文件
import { defineStore } from 'pinia';

// defineStore 函数接收两个参数的一个是string 它的id 必须是唯一的 第二个是对象如下
export const user = defineStore('user', {
  state: () => {
    return {
      name: '朱小明', 
      age: 24,
      // 很多数据......
    };
  },
  
  getters: {
    sum(){
      return 2*6
    }
   // 很多方法.......
  },
  
  actions: {
    changeAge(val) {
      this.age += val;
    },
    // 很多方法.......
  },
});

5.在组件中使用状态数据或者方法

import { storeToRefs } from 'pinia';
// 先引入user模块
import { user } from '../store/user';
const userStore = user(); // user 实例化

// 使用storeToRefs 函数可以将对实例化中的数据变为响应式
// 解构出来的变量可以直接用 {{ }} 在页面中直接展示
const { name, age, sum } = storeToRefs(userStore);


// 对pinia 的数据进行修改
// 第一种方式
const add = () => {
  userStore.age += 2;
};
// 第二种方式
const add2 = () => {
  userStore.$patch({
    name: '蘑菇头',
  });
};
// 第三种方式
const add3 = () => {
  userStore.$patch((state) => {
    state.age++;
    state.name = state.name === '朱小明' ? '蘑菇头' : '朱小明';
  });
};
// 第四种方式
const add4 = () => {
  // 在这里去调用 user模块中的 actions 里面的回调函数(类似于vuex中的提交触发)
  // 将修改的数据的方法写在 actions 的函数里面
};

// actions 的使用
// 首先需要在store 片段中定义好函数比如
 actions: {
    changeAge(val) {
      this.age += val;
    },
  },
  
// 然后在组件中使用实例来调取实例上面的方法 比如
const onadd = () => { 
  userStore.changeAge(5)
}


// getters 的使用
首先需要在store 片段中定义好函数比如
getters: {
    sum(){
      return 2*6
    }
  },
 
// 然后在组件中重实例上面解构出 sum 后可以直接将sum 在页面中展示
const { name, age, sum } = storeToRefs(userStore);

6.pinia的持久化存储

// 下载插件
npm i pinia-plugin-persistedstate

// 然后在store/index文件下引入插件并且集成
import { createPinia } from 'pinia';
// 引入插件
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate';
const store = createPinia();
// 在暴露store前先集成一下插件
store.use(piniaPluginPersistedstate);
export default store;

// 然后在模块文件进行配置调试比如在store/home.js 文件中
import { defineStore } from 'pinia';
export const homeStore = defineStore('home', {
  state: () => {
    return {
      title: '待办事件',
      v_show: false,
      // 很多数据
         lists: [
        {
          checkbox: false,
          text_content: '找工作',
          id: 1,
        },
        {
          checkbox: false,
          text_content: '学习知识',
          id: 2,
        },
        {
          checkbox: false,
          text_content: '爱你一万年',
          id: 3,
        },
      ],
    };
  },
  getters: {},
  actions: {},
  
  // 持久化存储的配置 默认配置
  persist: true,
});