【项目问题】Vue2和Vue3如何使用Pinia?数据持久化?防止storage被篡改?

本文介绍如何在Vue2与Vue3中使用Pinia进行状态管理,包括安装配置、创建store、使用state、getters及actions等核心功能,并提供了数据持久化的实现方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Pinia

Pinia 官方文档

Pinia 中文文档

在这里插入图片描述
在这里插入图片描述


Vue2中的使用

第一步:引入 Pinia

npm install pinia

在这里插入图片描述

第二步:在main.ts中全局引入

import { createPinia, PiniaVuePlugin } from 'pinia'

Vue.use(PiniaVuePlugin)
const pinia = createPinia()

new Vue({
  el: '#app',
  // other options...
  pinia,
})

第三步:创建store.js 文件

state

//store.js
import { defineStore } from 'pinia'

const useStore = defineStore('counterStore', {
    state: () => {
        return {
            counter: 0,
        }
    },
})

export default useStore;
<!--xx.vue-->
<template>
  <div>当前count的值:{{ counter }}</div>
</template>
<script>
import { mapState } from 'pinia'
import useCounterStore from '@/store'

export default {
  computed: {
    ...mapState(useCounterStore, ['counter'])
  },
}
</script>

在这里插入图片描述


getters

//store.js
import { defineStore } from 'pinia'

const useStore = defineStore('counterStore', {
    state: () => {
        return {
            counter: 2,
        }
    },
    getters: {
        doubleCounter(state) {
            return state.counter * 2
        }
    }
})

export default useStore;
<!--xx.vue-->
<template>
  <div>当前count的值:{{ doubleCounter }}</div>
</template>
<script>
import { mapState } from 'pinia'
import useCounterStore from '@/store'

export default {
  computed: {
    ...mapState(useCounterStore, ['doubleCounter'])
  },
}
</script>

在这里插入图片描述


actions

//store.js
import { defineStore } from 'pinia'

const useStore = defineStore('counterStore', {
    state: () => {
        return {
            counter: 1,
        }
    },
    getters: {
        doubleCounter(state) {
            return state.counter * 2
        }
    },
    actions: {
        increment() {
            this.counter++
        },
    }
})

export default useStore;
<!--xx.vue-->
<template>
  <div>当前count的值:{{ counter }}
    <button @click="increment">+1</button>
  </div>
</template>
<script>
import { mapActions, mapState } from 'pinia'
import useCounterStore from '@/store'

export default {
  computed: {
    //store中的state和getters
    ...mapState(useCounterStore, ['counter'])
  },
  methods: {
    //store中的actions
    ...mapActions(useCounterStore, ['increment'])
  }
}
</script>

在这里插入图片描述
在这里插入图片描述


Vue3中的使用

第一步:引入 Pinia

npm install pinia

在这里插入图片描述

第二步:在main.ts中全局引入

//main.ts
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'

const pinia = createPinia()
const app = createApp(App)

app.use(pinia).mount('#app')

第三步:创建store.ts文件

state

//store.ts
import { defineStore } from 'pinia' //引入 defineStore 定义仓库

export const useCounterStore = defineStore('counter', {
    state: () => ({ count: 0 }),//定义要进行存储的数据
})
<!--xx.vue-->
<template>
    <div>当前count的值:{{ store.count }}</div>
</template>

<script setup>
import { useCounterStore } from '../store'
const store = useCounterStore();
</script>

在这里插入图片描述


getters

//store.ts
import { defineStore } from 'pinia' //引入 defineStore 定义仓库

export const useCounterStore = defineStore('counter', {
    state: () => ({ count: 2 }),//定义要进行存储的数据
    getters: {
        doubleCount: (state) => state.count * 2,
    }
})
<!--xx.vue-->
<template>
    <div>当前count的值:{{ store.doubleCount }}</div>
</template>

<script setup>
import {useCounterStore} from '../store'
const store = useCounterStore()
</script>

在这里插入图片描述


actions

<!--xx.vue-->
<template>
    <div>当前count的值:{{ store.count }}
        <button @click="store.increment()">+1</button>
    </div>
</template>

<script setup>
import { useCounterStore } from '../store'
const store = useCounterStore()
</script>
//store.ts
import { defineStore } from 'pinia' //引入 defineStore 定义仓库

export const useCounterStore = defineStore('counter', {
    state: () => ({ count: 2 }),//定义要进行存储的数据
    actions: {
        increment() {
            this.count++
        },
    }
})

在这里插入图片描述

在这里插入图片描述

数据持久化(pinia-plugin-persist)

第一步:install pinia-plugin-persist

npm i pinia-plugin-persist --save

第二步:引入 pinia-plugin-persist

//main.js
import Vue from 'vue'
import App from './App.vue'
import { createPinia, PiniaVuePlugin } from 'pinia'
import piniaPluginPersist from 'pinia-plugin-persist'

Vue.use(PiniaVuePlugin)
const pinia = createPinia()
pinia.use(piniaPluginPersist)

window.vm = new Vue({
  render: h => h(App),
  pinia
}).$mount('#app')

第三步:设置数据缓存

import { defineStore } from 'pinia'

const useStore = defineStore('counterStore', {
    state: () => {
        return {
            counter: 1,
        }
    },
    getters: {
        doubleCounter(state) {
            return state.counter * 2
        }
    },
    actions: {
        increment() {
            this.counter++
        },
    },
    persist: {
        enabled: true,//开始数据缓存
        strategies: [
            {
                storage: localStorage,//默认是sessionStorage
                paths: ['counter'],//指定需要持久化存储的数据
            }
        ]
    }
})

export default useStore;

在这里插入图片描述
这样每次页面刷新的时候都不会把数据进行重置了!!!

开发者模式下localStorage或者SessionStorage被篡改怎么办?

在main文件中进行监听storage的监听,发生变化后用旧值进行替换

//防止localStorage被篡改
window.addEventListener('storage', e => {
  localStorage.setItem(e.key, e.oldValue)
})

//防止sessionStorage被篡改
window.addEventListener('storage', e => {
  sessionStorage.setItem(e.key, e.oldValue)
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@Dai

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值