vue3 中使用pinia,实现持久化存储

vuex与pinia对比

  1. 都支持选项式API和组合式API
  2. pinia没有mutations,只有:state,getters,actions
  3. pinia分模块不需要modules
  4. pinia的TS支持很好
  5. pinia可以自动化拆分代码
  6. pinia的体积更小,性能更好
  7. pinia可以直接修改数据,使用storeToRefs,直接修改pinia的值, vuex需要在计算属性中才能修改

pinia使用

安装:

npm i pinia

在main.ts中引入

import { createApp } from 'vue';
//挂载在app上
createApp(App).use(router).use(createPinia()).mount('#app');

新建store文件夹,新建index.ts

import { defineStore } from 'pinia';
export const userStore = defineStore('storeId', {
  state: () => {
    return {
      num: 17,
      age: '48',
      name: '苦哈哈',
    };
  },
  getters: {
    changeNum() {
      return this.num + 10;
    },
  },
  // 同步和异步都可以写
  actions: {
    upNum(val) {
      this.num += val;
    },
  },
});

在文件中使用







模块划分

pinia可以根据名称直接划分模块,不需要借助modules
新建user.ts,shop.ts

import { defineStore } from 'pinia';
export const user = defineStore('user', {
  state: () => {
    return {
      username: 'Admin',
    };
  },
  getters: {
    changeNum() {
      return this.username + '今天是周三';
    },
  },
  actions: {
    changeUsername(val){
      this.username = val
    }
  },
});

import { defineStore } from 'pinia';
export const shop = defineStore('shop', {
  state: () => {
    return {
      goods: ['鞋子', '珠宝', '包包'],
      akf: '0000000',
    };
  },
  getters: {
    changeGoods() {},
  },
  actions: {
    changeCoodsname() {},
  },
});

在文件中使用







pinia持久化

npm i  pinia-plugin-persistedstate -S

在main.ts中引用

import piniaStore from './store';
createApp(App).use(router).use(piniaStore).mount('#app');

index.ts

import { createPinia } from 'pinia';
import { useAppStore } from './modules/app';
import { useUserStore } from './modules/user';

import piniaPluginPersistedstate from 'pinia-plugin-persistedstate';

const pinia = createPinia();
pinia.use(piniaPluginPersistedstate);

export { useAppStore, useUserStore };
export default pinia;

app.ts

import { createPinia } from 'pinia';
import { useAppStore } from './modules/app';
import { useUserStore } from './modules/user';
//引入持久化
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate';

const pinia = createPinia();
pinia.use(piniaPluginPersistedstate);
//使用插件
export { useAppStore, useUserStore };
export default pinia;

在模块中开启缓存

import { defineStore } from 'pinia';
import piniaStore from '/@/store/index';

export const useAppStore = defineStore(
  // 唯一ID
  'app',
  {
    state: () => ({
      title: 'FastVue3,一个快速开箱即用的Vue3+Vite模板',
    }),
    getters: {},
    actions: { },
    //配置缓存
    persist: {
      key: 'theme',
      //存储在localstorage还是sessionStorage中
      storage: localStorage,
      //哪个数据需要持久化
      paths: ['theme'],
    },
  },
);

你可能感兴趣的:(typescript,前端,vue.js)