Vue3 使用Pinia状态管理

安装

npm install pinia --save

使用

创建store文件夹

建 src/store 目录并在其下面创建 index.ts,导出 store

// src/store/index.ts
import { createPinia } from 'pinia'

const store = createPinia()

export default store

在 main.ts 中引入并使用

// src/main.ts

import { createApp } from 'vue'
import App from './App.vue'
import store from './store'

const app = createApp(App)
app.use(store)

创建login.ts文件

建 src/store 目录并在其下面创建 module/login.ts文件,用来单独管理各个模块

// src/store/module/login.ts
import { ref } from 'vue'
import { defineStore } from 'pinia'

export const useLoginStoreSetup = defineStore('useLoginStoreSetup', {
  // Composition API写法
  // const count = ref<number>(0)
  // const getCount = () => {
  //   return count.value * 2
  // }
  // const incurment = () => {
  //   count.value++
  // }

  // return {
  //   count,
  //   getCount,
  //   incurment
  // }

  // options API写法
  state: () => ({
    count: 0,
	sum: 0
  }),
  getters: {
    dobule: (state) => state.count
  },
  actions: {
    incurment() {
      this.count++
	  this.sum++
    },
  }
})

获取store

直接解构会失去响应式: 但是可以通过以下两种方式获取
方式1: 通过计算属性获取
方式2: 通过pinia 内置方法storeToRefs()

// login.vue
<template>
  <div class="layout-wrap login-wrap">
    <el-button @click="handleBtn">获取</el-button>
    <div>pinia的state: count会失去响应 = {{ count }}</div>
    <div>pinia的state: sum通过storeToRefs获取不会失去响应 = {{ sum }}</div>
    <div>pinia的getters: dobule = {{ dobule }}</div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useLoginStoreSetup } from '@/store/module/login'
export default defineComponent({
  setup() {
    const store = useLoginStoreSetup()
    const { incurment, count } = store // 直接解构会使count失去响应式
 // const count = computed(() => store.count) 方式1: 可以通过计算属性
    const { dobule, sum } = storeToRefs(store) // 方式2: 通过storeToRefs解构sum不会失去响应
    const handleBtn = () => {
      incurment()
    }
    return {
      handleBtn,
      count,
      sum,
      dobule
    }
  }
})
</script>

image

数据持久化

npm i pinia-plugin-persist --save

引入插件

// src/store/index.ts
import { createPinia } from 'pinia'
import piniaPluginPersist from 'pinia-plugin-persist' //+

const store = createPinia() //+
store.use(piniaPluginPersist)

export default store

默认配置

数据默认存在 sessionStorage 里,
并且会以 store 的 id 作为 key。

// src/store/module/login.ts
export const useLoginStoreSetup = defineStore('useLoginStoreSetup', {
  // options API写法
  state: () => ({
    count: 0,
    token: '',
    userInfo: {}
  }),

  // 开启数据缓存
  persist: {
    enabled: true
  }
})

image

自定义key

自定义 存储 key 值,
并将存放位置由 sessionStorage 改为 localStorage。
这里默认缓存state里所有的值

// src/store/module/login.ts
export const useLoginStoreSetup = defineStore('useLoginStoreSetup', {
  // options API写法
  state: () => ({
    count: 0,
    token: '',
    userInfo: {}
  }),

  // 开启数据缓存
	persist: {
	  enabled: true,
	  strategies: [
		{
		  key: 'my_user',
		  storage: localStorage,
		}
	  ]
	}
})

image

持久化部分 state

默认所有 state 都会进行缓存
可以通过 paths 指定要持久化的字段,其他的则不会进行持久化

// src/store/module/login.ts
export const useLoginStoreSetup = defineStore('useLoginStoreSetup', {
  // options API写法
  state: () => ({
    count: 0,
    token: '',
    userInfo: {}
  }),

  // 开启数据缓存
  persist: {
    enabled: true,
    strategies: [
      {
        storage: localStorage,
        paths: ['userInfo', 'token']
      }
    ]
  }
})

上面我们只持久化 name 和 age,并将其改为localStorage,
gender 不会被持久化,如果其状态发送更改,页面刷新时将会丢失,重新回到初始状态,
而 name 和 age 则不会。
image

posted @ 2022-02-26 00:04  飞鸟和蝉-  阅读(900)  评论(0编辑  收藏  举报