【Vue3】Pinia $subscribe

背景

随着年龄的增长,很多曾经烂熟于心的技术原理已被岁月摩擦得愈发模糊起来,技术出身的人总是很难放下一些执念,遂将这些知识整理成文,以纪念曾经努力学习奋斗的日子。本文内容并非完全原创,大多是参考其他文章资料整理所得,感谢每位技术人的开源精神。

简介

本文介绍 Vue3 中如何使用 Pinia $subscribe 实现 state 数据监听。

Pinia 是 Vue 专属的状态管理库,允许跨组件或页面共享数据。

开发环境

分类名称版本
操作系统WindowsWindows 11
IDEVisual Studio Code1.91.1

开发步骤及源码

1> 在 【Vue3】Pinia存储及读取数据 基础上修改功能组件 Book.vue,使用 Pinia $subscribe 监听 store 中数据变换,每次数据变化后都写入本地存储(localStorage.setItem)。

<template>
    <div class="books">
        <h2>图书数量:{{ bookCount }}</h2>
        <h2>图书列表</h2>
        <ul>
            <li v-for="book in books" :key="book.id">
                {{ book.title }} -- {{ book.author }}
            </li>
        </ul>
    </div>
</template>

<script setup lang="ts">
import { useBookStore } from '@/store/book'
import { storeToRefs } from 'pinia';

const bookStore = useBookStore()
const { bookCount, books } = storeToRefs(bookStore)

bookStore.$subscribe((mutate, state) => {
    console.log('store数据发生了变化')
    console.log('本次修改数据:', mutate)
    console.log('当前最新数据:', state)
    localStorage.setItem('bookCount', JSON.stringify(state.bookCount))
    localStorage.setItem('books', JSON.stringify(state.books))
})
</script>

<style scoped lang="scss">
.books {
    background-color: aquamarine;
    padding: 20px;
    li {
        font-size: 20px;
        height: 35px;
        line-height: 35px;
    }
}
</style>

2> 修改 src/store/book.tsstate 中数据不再是写死的,改成先从本地存储中读取(localStorage.getItem),如果读取不到再赋予固定的初始值。

import { defineStore } from "pinia"

interface Book {
    id: string
    title: string
    author: string
    category: string
}

export const useBookStore = defineStore('book', {
    // state 必须写成函数形式,返回的对象即是集中存储的数据
    state() {
        return {
            bookCount: localStorage.getItem('bookCount') || 6,
            books: JSON.parse(localStorage.getItem('books') as string) || [
                { id: '001', title: '坐天下', author: '张宏杰', category: "历史" },
                { id: '002', title: '明朝那些事儿', author: '当年明月', category: "历史" },
                { id: '003', title: '太白金星有点烦', author: '马伯庸', category: "小说" },
                { id: '004', title: '活着', author: '余华', category: "小说" },
                { id: '005', title: '饥饿的盛世', author: '张宏杰', category: "历史" },
                { id: '006', title: '镖人', author: '许先哲', category: "漫画" },
            ]
        }
    },
    getters: {
        history(state) {
            return state.books.filter((book: Book) => book.category == "历史").length
        },
        novel: state => state.books.filter((book: Book) => book.category == "小说").length,
        comic(): number {
            return this.books.filter((book: Book) => book.category == "漫画").length
        }
    }
})

3> 新增功能组件 Reader.vue 修改 Pinia 中数据。

<template>
    <div class="reader">
        <button @click="borrow">借阅</button>
    </div>
</template>

<script setup lang="ts">
import { useBookStore } from '@/store/book'

const bookStore = useBookStore()

function borrow() {
    (bookStore.bookCount as number) -= 1
    bookStore.books.shift()
}
</script>

<style scoped lang="scss">
.reader {
    background-color: darkcyan;
    padding: 20px;
    button {
        font-size: 20px;
        height: 40px;
        line-height: 40px;
        margin-right: 10px;
        width: 120px;
    }
    li {
        color: white;
        font-size: 20px;
        height: 35px;
        line-height: 35px;
    }
}
</style>

4> 修改 src/App.vue,引入新添加的功能组件 Reader.vue

<template>
  <div class="content">
    <Book />
    <hr>
    <Reader />
  </div>
</template>

<script setup lang="ts">
import Book from './components/Book.vue'
import Reader from './components/Reader.vue'
</script>

<style scoped lang="scss">
.content {
  background-color: darkgray;
  padding: 20px;
}
</style>

5> 执行命令 npm run dev 启动应用,浏览器访问:http://localhost:5173/。点击 借阅 按钮修改 Pinia 中数据后,先关闭浏览器,然后再次打开浏览器访问 http://localhost:5173/,发现显示的仍然是上次修改后的数据。数据监听日志如下:
在这里插入图片描述

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

又言又语

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

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

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

打赏作者

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

抵扣说明:

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

余额充值