Pinia 状态管理器 菠萝:Option Store风格

Pinia介绍:

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

Pinia 大小只有 1kb 左右,超轻量级,你甚至可能忘记它的存在!

相比 Vuex,Pinia 的优点:

  • 更贴合 Vue 3 的 Composition API 风格,学习成本更低
  • 不需要像Vuex中要区分 Mutation 和 Action,Pinia统一使用 Actions 操作状态
  • 支持 TypeScript,可以充分利用 TS 的静态类型系统
  • 模块化管理 States, 每个模块是一个 Store
  • 直观的 Devtools,可以看到每个 State 的变化

安装:

npm install pinia

# 或者

yarn add pinia

案列:

/src/router/index.js 路由器

import { createRouter, createWebHashHistory,createWebHistory } from "vue-router"; //导入vue-router路由模块,createWebHashHistor函数
//import Home from "../views/Home.vue" //异步加载的组件,这里不需要
//import List from "../views/List.vue" //异步加载的组件,这里不需要进行导入,所以要注释掉

const routes = [
    {
        path: "/",  //路径:        
        redirect: {
            name: "ListA" //重定向到路由名称为mylist的路由中,这样当浏览器输入的是:http://localhost:5173/ 则会重定向跳转到 http://localhost:5173/list
        }
    },
    {
        path: "/lista",  //路径
        //当路由被触发时,该组件才会被异步加载,举列:打开页面就不会加载所有的组件,而是根据当前页面需要的组件进行异步加载
        //这样可以减少初始加载时间,提升用户体验,同时也节省了不必要的资源消耗。
        name:"ListA",
        component: () => import("../views/ListA.vue")

    },
    {
        path: "/listb",  //路径
        //当路由被触发时,该组件才会被异步加载,举列:打开页面就不会加载所有的组件,而是根据当前页面需要的组件进行异步加载
        //这样可以减少初始加载时间,提升用户体验,同时也节省了不必要的资源消耗。
        name:"ListB",
        component: () => import("../views/ListB.vue")

    }  
]

//创建路由对象
const router = createRouter({
    //history:createWebHashHistory()   这种方式是按照hash路由模式来路由导航,这种路由模式的url地址会存在 /#/ 样式是:http://localhost:5173/#/list
    history: createWebHistory(),     //这种方式基于浏览器 history API 的路由模式,url的样式是:http://localhost:5173/list
    routes, //routes:routes的缩写

})

export default router //导出router路由对象//导出router路由对象

Pinia状态管理器:模块

/src/store/useListAStore.js  ListA.vue组件单独使用的状态管理器模块

/*
    js文件的命名建议:use+组件名称+Store  举列:用于ListA组件的store 我的取名就是 useListAStore.js
*/

import { defineStore } from 'pinia'
import axios from 'axios'

// Option Store风格案列演示:如下

//第一个参数是唯一的storeId
//第二个参数是一个对象
const useListAStore = defineStore("ListAStoreId", {
    // 为了完整类型推理,推荐使用箭头函数
    state: () => {
        return {
            // 所有这些属性都将自动推断出它们的类型
            name: 'Eduardo',
            age: 20,
            email: 'abc@qq.com',
            datalist: [],
        }
    },
    actions: {
        getDataList() {
            const result = async axios({
                url: "https://m.maizuo.com/gateway?cityId=110100&pageNum=1&pageSize=10&type=1&k=7069698",
                headers: {
                    'X-Client-Info': '{"a":"3000","ch":"1002","v":"5.2.1","e":"16992764191480200349024257"}',
                    'X-Host': 'mall.film-ticket.film.list'
                }
            })
            this.datalist = result.data.data.films
        },
        async changeName(newname) {
            this.name = newname;
        }
    },
    getters: {
        filterDataList(state) {
            return (keyword) => {
                return state.datalist.filter(item => item.name.includes(keyword));
            }
        }
    },
})

export default useListAStore //导出

/src/store/useListBStore.js    ListB.vue组件单独使用的状态管理器模块

/*
    js文件的命名建议:use+组件名称+Store  举列:用于ListA组件的store 我的取名就是 useListAStore.js
*/

import { defineStore } from 'pinia'
import axios from 'axios'

// Option Store风格案列演示:如下

//第一个参数是唯一的storeId,注意别与其它模块的storeId重名(其实这个storeId我们开发人员一般用不到)
//第二个参数是一个对象
const useListBStore = defineStore("ListBStoreId", {
    // 为了完整类型推理,推荐使用箭头函数
    state: () => {
        return {
            // 所有这些属性都将自动推断出它们的类型
            name: '张三',
            datalist: [],
        }
    },
    actions: {
        async getDataList() {
            //异步
            const result = await axios({
                url: "https://m.maizuo.com/gateway?cityId=110100&ticketFlag=1&k=3777796",
                headers: {
                    'X-Client-Info': '{"a":"3000","ch":"1002","v":"5.2.1","e":"16992764191480200349024257","bc":"110100"}',
                    'X-Host': 'mall.film-ticket.cinema.list'
                }
            });
            this.datalist = result.data.data.cinemas
        },

        async changeName(newname) {
            this.name = newname;
        }
    },
    getters: {
        filterDataList(state) {
            return (type) => {               
                return state.datalist.filter(item => item.eTicketFlag == type)
            }
        }
    },
})

export default useListBStore //导出

注册:路由器 和 状态管理器

import { createApp } from 'vue'
import './style.css'
import App from './App.vue'


import router from "../src/router/index.js" //导入状态管理器js 
//import store from "../src/store/index.js" //导入状态管理器js 

import { createPinia} from 'pinia' //导入状态管理器js 
const pinia=createPinia();

var app=createApp(App)
app.use(router);
app.use(pinia); //注册pinia状态管理器 菠萝

//app.use(store)  //注册vuex插件:状态管理器

app.mount("#app")

使用:

ListA.vue组件:电影列表

<template>
    <div>
        <div>
            <!-- 从useListAStore.js模块下的state中取数:获取useListAStore.js模块下state中的name -->
            姓名: {{ store.name }}
        </div>
        <input type="text" v-model.lazy="keyword" placeholder="搜索">
        <ul>
            <!-- 从useListAStore.js模块下的Getters中取数:执行Getters中的filterDataList方法 -->
            <li v-for="item in store.datalist" :key="item.filmId">{{ item.name }}</li>
        </ul>
    </div>
</template>
<script setup>
// VCA中不支持辅助函数,因为辅助函数中是用this.$store,而VCA中没有绑定this的
import { useStore } from 'vuex'
import { ref, onMounted, onBeforeUnmount } from 'vue'
import useListAStore from '../store/useListAStore.js'

const store = useListAStore();

store.changeName("王五");

//$patch的用法:

// store.name="张三";
// store.age=30;
// store.email="123@qq.com";
// 上面三条数据的修改,可以用store.$patch方法统一修改:如下:
// store.$patch({
//     name:"张三",
//     age:30,
//     email:"123@qq.ccom"
// })


const keyword = ref("");
onMounted(() => {
    if (store.datalist.length === 0) {
        store.getDataList();  //执行useListAStore.js模块中Actions中的getDataList方法  
    }
})

onBeforeUnmount(() => {
    store.$reset() //对useListAStore.js模块下store里面state中的所有数据进行重置:注意是重置
})


</script>
<style scoped>
li {
    padding: 10px;
}
</style>

ListB.vue组件:影院列表

<template>
    <div>
        <!-- 从store中的state中取数:获取useListBStore.js模块state中的name -->
        <div> 姓名:{{ store.name }}</div>
        <select v-model="type">
            <option :value="0">APP订票</option>
            <option :value="1">前台兑换</option>
        </select>
        <ul>
            <!-- 从store中的Getters中取数:执行useListBStore.js模块Getters中的filterDataList方法 -->
            <li v-for="item in store.filterDataList(type)" :key="item.cinemaId"> {{ item.name }}
            </li>
        </ul>
    </div>
</template>
<script setup>
// VCA中不支持辅助函数,因为辅助函数中是用this.$store,而VCA中没有绑定this的

import { ref, onMounted } from 'vue'
import useListBStore from '../store/useListBStore.js' 
const store = useListBStore();

const type = ref(0);
onMounted(() => {
    if (store.datalist.length === 0) {
        store.getDataList(); //执行useListBStore.js模块中Actions中的getDataList方法
    }
})
</script>

App.vue根组件

<template>
  <div>
    <div>{{store.name}}</div>
    <ul class="nvabar">
            <RouterLink custom to="/ListA" v-slot="{ isActive, navigate }">
                <li @click="navigate">
                    <span :class="isActive ? 'highlighter' : ''">电影列表</span>
                </li>
            </RouterLink>
            <RouterLink custom to="/ListB" v-slot="{ isActive, navigate }">
                <li @click="navigate">
                    <span :class="isActive ? 'highlighter' : ''">影院列表</span>
                </li>
            </RouterLink>
        </ul>
    <router-view></router-view>
  </div>
</template>
<script setup>
import { ref, } from 'vue';

import ListA from "./views/ListA.vue" //导入Home组件:
import ListB from "./views/ListB.vue" //导入List组件:

import useListAStore from './store/useListAStore.js'


const store=useListAStore();

</script>
<style scoped>
.nvabar {
    /*固定定位:元素的位置相对于浏览器窗口是固定位置。即使窗口是滚动的它也不会移动*/
    /* position: fixed; */
    /*显示在底部*/
    /* bottom: 0; */
    display: flex;
    /* width: 100%; */
    height: 50px;
    line-height: 50px;
    text-align: center;
}
 
.nvabar li {
    flex: 1;
    list-style-type: none;
}
 
.highlighter {
     /* 高亮 */
    color: red;
    border-bottom: 3px solid red;
    padding-bottom: 7px;
   
}
</style>

效果图

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/135906.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【Python】KDtree的调用

前言 查询点集中与目标点最近的k个点 from scipy.spatial import cKDTree import numpy as npdata np.array([[1,2],[1,3],[4,5]]) # 生成 100 个三维数据 tree cKDTree(data) # 创建 K-D Tree result tree.query(np.array([5, 5]), k2) # 查询与 [0.5, 0.5, 0.5] 最近的三…

Jvm虚拟机

问题&#xff1a; 计算机能识别的语言是二进制&#xff0c;Java文件是程序员编写的&#xff0c;如何能够在计算机上运行&#xff1f; 以及Java为什么可以实现跨平台&#xff1f; 一Java的jdk中有jvm虚拟机 可以将文件转换为字节码文件 使得它可以在各种平台上运行&#xff0c;这…

计算机组成原理之处理器(流水线)

引言 为什么不采用单周期实现,硬件比较简单&#xff1f; 主要是因为效率太低&#xff0c;处理器中最长的路径&#xff08;一般是ld指令)决定了时钟周期 流水线概述 流水线是一种能使多条指令重叠执行的技术。 流水线更快的原因是所有的工作都在并行执行&#xff0c;所以单位…

按键编程 pal库和标准库

按钮的电路设计 电路的搭建 原理与编程 创建了两个变量 用来捕捉按键的状态 先让两个变量都为1 previous和current都为1 &#xff08;按键没按下&#xff09; 然后让current去捕捉按键的状态通过读gpioA的pin0 如果为0就是按键按下 如果为1就是按键没按下 然后赋值给current …

论文笔记:Deep Trajectory Recovery with Fine-Grained Calibration using Kalman Filter

TKDE 2021 1 intro 1.1 背景 用户轨迹数据对于改进以用户为中心的应用程序很有用 POI推荐城市规划路线规划由于设备和环境的限制&#xff0c;许多轨迹以低采样率记录 采样的轨迹无法详细说明物体的实际路线增加了轨迹中两个连续采样点之间的不确定性——>开发有效的算法以…

哈希表之闭散列的实现

闭散列实现哈希表 在闭散列实现哈希表中&#xff0c;我们选择线性探测法来解决哈希冲突。在哈希表的简介部分&#xff0c;我们已经介绍过线性探测法啦&#xff01; 线性探测&#xff1a;从发生冲突的位置开始&#xff0c;依次向后探测&#xff0c;直到寻找到下一个空位置为止…

Carla之语义分割及BoundingBox验证模型

参考&#xff1a; Carla系列——4.Cara模拟器添加语义分割相机&#xff08;Semantic segmentation camera&#xff09; Carla自动驾驶仿真五&#xff1a;opencv绘制运动车辆的boudingbox&#xff08;代码详解&#xff09; Carla官网Bounding Boxes Carla官网创建自定义语义标签…

【离散数学必刷题】谓词逻辑(第二章 左孝凌版)刷完包过!

专栏&#xff1a;离散数学必刷题 本章需要掌握的重要知识&#xff1a; 1.利用谓词表达式表示命题 2.变元的约束 3.谓词公式的定义、谓词公式的赋值 4.谓词公式的翻译&#xff08;注意在全总个体域时使用特性谓词&#xff09; 5.有限论域上量词的消去 6.谓词公式中关于量词的等价…

软件工程——名词解释

适用多种类型的软件工程教材&#xff0c;有关名词释义的总结较为齐全~ 目录 1. 软件 2. 软件危机 3. 软件工程 4. 软件生存周期 5. 软件复用 6. 质量 7. 质量策划 8. 质量改进 9. 质量控制 10. 质量保证 11. 软件质量 12. 正式技术复审 13. ISO 14. ISO9000 15.…

思维模型 暗示效应

本系列文章 主要是 分享 思维模型&#xff0c;涉及各个领域&#xff0c;重在提升认知。无形中引导他人的思想和行为。 1 暗示效应的应用 1.1 暗示效应在商业品牌树立中的应用 可口可乐的品牌形象&#xff1a;可口可乐通过广告、包装和营销活动&#xff0c;向消费者传递了一种…

macOS使用conda初体会

最近在扫盲测序的一些知识 其中需要安装一些软件进行练习&#xff0c;如质控的fastqc&#xff0c;然后需要用conda来配置环境变量和安装软件。记录一下方便后续查阅学习 1.安装miniconda 由于我的电脑之前已经安装了brew&#xff0c;所以我就直接用brew安装了 brew install …

基于STC12C5A60S2系列1T 8051单片机定时器/计数器应用

基于STC12C5A60S2系列1T 8051单片机定时器/计数器应用 STC12C5A60S2系列1T 8051单片机管脚图STC12C5A60S2系列1T 8051单片机I/O口各种不同工作模式及配置STC12C5A60S2系列1T 8051单片机I/O口各种不同工作模式介绍STC12C5A60S2系列1T 8051单片机定时器/计数器介绍STC12C5A60S2系…

BGP基本配置实验

目录 一、实验拓扑 二、实验需求 三、实验步骤 1、IP地址配置 2、内部OSPF互通&#xff0c;配置OSPF协议 3、BGP建立邻居关系 4、R1和R5上把业务网段宣告进BGP 5、消除路由黑洞&#xff0c;在R2、R4上做路由引入 6、业务网段互通 一、实验拓扑 二、实验需求 1、按照图…

Gold-YOLO:基于收集-分配机制的高效目标检测器

文章目录 摘要1、简介2、相关工作2.1、实时目标检测器2.2、基于Transformer的目标检测2.3、用于目标检测的多尺度特征 3、方法3.1、预备知识3.2、低级收集和分发分支3.3、高阶段收集和分发分支3.4、增强的跨层信息流3.5、遮罩图像建模预训练 4、实验4.1、设置4.2、比较4.3.2、 …

Android14前台服务适配指南

Android14前台服务适配指南 Android 10引入了android:foregroundServiceType属性&#xff0c;用于帮助开发者更有目的地定义前台服务。这个属性在Android 14中被强制要求&#xff0c;必须指定适当的前台服务类型。以下是可选择的前台服务类型&#xff1a; camera: 相机应用。…

Git之分支与版本

&#x1f3ac; 艳艳耶✌️&#xff1a;个人主页 &#x1f525; 个人专栏 &#xff1a;《Spring与Mybatis集成整合》《Vue.js使用》 ⛺️ 越努力 &#xff0c;越幸运。 1.开发测试上线git的使用 1.1. 环境讲述 当软件从开发到正式环境部署的过程中&#xff0c;不同环境的作用…

docker搭建etcd集群

最近用到etcd&#xff0c;就打算用docker搭建一套&#xff0c;学习整理了一下。记录在此&#xff0c;抛砖引玉。 文中的配置、代码见于https://gitee.com/bbjg001/darcy_common/tree/master/docker_compose_etcd 搭建一个单节点 docker run -d --name etcdx \-p 2379:2379 \…

matlab Silink PID 手动调参

&#xff08;业余&#xff09;PID即比例积分微分&#xff0c;它将给定值r(t)与实际输出值y(t)的偏差的比例(P)、积分(I)、微分(D)通过线性组合形成控制量&#xff0c;对被控对象进行控制。我们先用matlab Silink弄一个简易的PID例子&#xff1a; 中间三条就是比例&#xff0c;积…

Django中简单的增删改查

用户列表展示 建立列表 views.py def userlist(request):return render(request,userlist.html) urls.py urlpatterns [path(admin/, admin.site.urls),path(userlist/, views.userlist), ]templates----userlist.html <!DOCTYPE html> <html lang"en">…

大数据可视化数据大屏可视化模板【可视化项目案例-05】

🎉🎊🎉 你的技术旅程将在这里启航! 🚀🚀 本文选自专栏:可视化技术专栏100例 可视化技术专栏100例,包括但不限于大屏可视化、图表可视化等等。订阅专栏用户在文章底部可下载对应案例源码以供大家深入的学习研究。 🎓 每一个案例都会提供完整代码和详细的讲解,不…