第九节 再说Vue3项目中安装Pinia和Pinia持久化插件

亮子 2024-04-04 02:32:37 22712 0 0 0

上一节的持久化,我在实际测试中,并没有效果,目前还不清楚是自己哪里的代码有问题,因此,我又换了一个pinia的持久化的插件,这个插件测试是没有问题。

1、安装插件

pnpm i pinia-plugin-persistedstate

2、在main.ts文件中引入

import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'

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

3、使用

import { defineStore } from 'pinia'

export const useStore = defineStore(
  'main',
  () => {
    const someState = ref('你好 pinia')
    return { someState }
  },
  {
    persist: true,
  },
)

4、示例代码

// filename: main.ts
import './assets/main.css'

import { createApp } from 'vue'
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'

import App from './App.vue'
import router from './router'

import ElementPlus from 'element-plus'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import 'element-plus/dist/index.css'

const app = createApp(App)

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

app.use(pinia)
app.use(router)

app.use(ElementPlus, {
    locale: zhCn,
  })

app.mount('#app')

图片alt