【Vue3】Pinia getters

背景

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

简介

本文介绍 Vue3 中如何使用 Pinia getters

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

gettersdefineStore 的三个属性之一,可以理解为 state 的计算属性。

开发环境

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

开发步骤及源码

1> 在 【Vue3】Pinia存储及读取数据 基础上修改 src/store/book.ts,补充 defineStoregetters 属性,分别统计历史类、小说类、漫画类图书数量。

import { defineStore } from "pinia"

export const useBookStore = defineStore('book', {
    // state 必须写成函数形式,返回的对象即是集中存储的数据
    state() {
        return {
            bookCount: 6,
            books: [
                { 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.category == "历史").length
        },
        novel: state => state.books.filter(book => book.category == "小说").length,
        comic(): number {
            return this.books.filter(book => book.category == "漫画").length
        }
    }
})

此处展示了 3 种 getters 下函数的写法。

2> 修改功能组件 src/components/Book.vue,显示历史类、小说类、漫画类图书数量。

<template>
    <div class="books">
        <h2>图书数量:{{ bookCount }}</h2>
        <h2>历史类:{{ history }}</h2>
        <h2>小说类:{{ novel }}</h2>
        <h2>漫画类:{{ comic }}</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, history, novel, comic } = storeToRefs(bookStore)
</script>

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

3> 执行命令 npm run dev 启动应用,浏览器访问:http://localhost:5173/
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

又言又语

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

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

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

打赏作者

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

抵扣说明:

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

余额充值