Vue3 使用pinia+pinia-plugin-persist setup写法

最近项目技术更新,决定用vitejs+vue3+pinia重写项目。我们决定一步到位直接script setup方式来写,边学边写边记录:

1、先安装

npm i pinia-plugin-persist

2、引入

import {createPinia} from 'pinia'
import App from './App.vue'
import router from './router/index'
import piniaPersistPlugin from 'pinia-plugin-persist'

const app = createApp(App)
const pinia = createPinia()
pinia.use(piniaPersistPlugin)
app.use(pinia)
app.use(router)
app.mount('#app')

3、在store/index.ts中构建store的总管理

import {defineStore} from 'pinia'
import {ref} from 'vue'
import loginStore from './loginStore'
const useAppStore = defineStore(
  'appStore',
  () => {
    let loadNum = ref(0)
    const hideLoading = () => {
      loadNum.value--
    }
    const showLoading = () => {
      loadNum.value++
    }
    const isLoading = () => {
      return loadNum.value > 0
    }
    return {
      hideLoading,
      showLoading,
      isLoading
      // loadNum要持久化保存到本地一定要加,当然不加数据响应是没问题的,isLoading也会重新计算,就是不会保存
    }
  }
  //作为第三个参数配置
  // {
  //   persist: {
  //     enabled: true,
  //     strategies: [{storage: localStorage, paths: ['loadNum']}]
  //   }
  // }
)

export default {
  loginStore,
  useAppStore
}

4、ui上的使用




5、看效果

点击之后Vue3 使用pinia+pinia-plugin-persist setup写法_第1张图片

 

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