• pinia简单使用及持久化


    pinia使用

    安装

    npm i pinia --save

    新建store目录,创建index.ts

    import { createPinia } from "pinia";
    
    const store = createPinia();
    
    export default store;

    main.ts中使用store

    import { createApp } from 'vue'
    import store from './store'
    
    const app = createApp(App)
    app.use(store)
    app.mount('#app')

    新建user.ts

    import { defineStore } from "pinia";
    
    export const useUserStore = defineStore({
      id:'user',
      state() {
        return {
          name: '',
          age: null,
        }
      }
    })

    在vue页面中使用

    template中
    <template>
        <p>姓名:{{name}}</p>
        <p>年龄:{{age}}</p>
    </template>
    script中
    import { storeToRefs } from 'pinia'
    import { useUserStore } from '../../store/module/user';
    
    const store = useUserStore();
    const { name, age } = storeToRefs(store)

    修改store中的值

    import { useCurrentMenuStore } from '../../store/module/menu';
    
    const store = useCurrentMenuStore();
    
    const changeUserInfo = () => {
        store.name = '修改的name';
        store.age = '修改的age'
    }

    pinia持久化

    安装

    npm i pinia-plugin-persist --save

    修改store文件夹下的index.ts

    import { createPinia } from "pinia";
    import piniaPluginPersist from 'pinia-plugin-persist'
    
    const store = createPinia();
    store.use(piniaPluginPersist);
    
    export default store;

    修改需要持久化的store模块:添加persist,storage默认是sessionStorage

    import { defineStore } from "pinia";
    
    export const useUserStore = defineStore({
      id:'user',
      state() {
        return {
          name: '',
          age: null,
        }
      },
      persist: {
        enabled: true,
        strategies: [
          {
              key: 'user',
              storage: localStorage,
          }
        ]
      }
    })
  • 相关阅读:
    仿照everything写的一个超级速查 原创
    [转]SharePoint 2013 Online App Development – Part 1
    [转]SharePoint 2013 App 开发 (2)
    [转]ASP.NET自定义控件复杂属性声明持久性浅析
    HasRights方法参数
    故障分析神器——BTrace
    JVM——Memory Analyzor分析内存溢出
    关于句柄
    Java内存区域与内存溢出
    命令行的使用
  • 原文地址:https://www.cnblogs.com/chenwan1218/p/16136072.html
Copyright © 2020-2023  润新知