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,
      }
    ]
  }
})
复制代码

 页面中使用pinia数据,pinia数据更新时,页面数据不更新

使用时用计算属性computed

1
2
3
import useCommonStore from '@/stores';
 
const currentPath = computed (()=> useCommonStore().currentPath)

  

posted @   吃饭睡觉打痘痘  阅读(827)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示