【vue3】pinia配置(任意组件通信,集中状态管理容器)

选择式写法

一、安装pinia依赖

终端输入:npm install pinia

二、配置pinia

第一步:创建仓库,在src目录下创建文件夹modules和文件index.ts.
第二步:配置index.ts

javascript 复制代码
// 创建pinia大仓库
import { createPinia } from "pinia";
let store = createPinia();
export default store;

第三步:在main.ts引入

第四步(案例):配置小仓库info

javascript 复制代码
import { defineStore } from "pinia";
// defineStore("仓库名","仓库的基础配置")
let useInfoStore = defineStore("info", {
  // 存储数据
  state: () => {
    return {
      name: "zs",
      age: 1,
    };
  },
  actions: {
    changeAge() {
      this.age++;
    },
  },
  getters: {
    c() {
      let s: string = this.name + this.age;
      return s;
    },
  },
});
export default useInfoStore;

第五步:组件调用小参考数据

组合式写法

javascript 复制代码
import { defineStore } from "pinia";
import { ref, computed } from "vue";

let useToolStore = defineStore("tool", () => {
  let tool = ref([
    { name: "lisi", age: 12 },
    { name: "wangwu", age: 14 },
  ]);
  let arr = ref([1,2,3]);
  const c = computed(() => {
    return arr.value.reduce((pre: any, next: any) => {
      return pre + next;
    },0);
  });
  return {
    tool,
    arr,
    updateAge() {
      tool.value.push({ name: "xx", age: 66 });
    },
    c,
  };
});
export default useToolStore;
相关推荐
冴羽5 小时前
100s 带你了解 Bun 为什么这么火
前端·node.js·bun
Sylvia33.5 小时前
火星数据:解构斯诺克每一杆进攻背后的数字语言
java·前端·python·数据挖掘·数据分析
TT_Close5 小时前
“啪啪啪”三下键盘,极速拉起你的 uni-app 项目!
vue.js·uni-app·前端工程化
柯南95275 小时前
Electron 无边框窗口拖拽实现
vue.js·electron
Wect5 小时前
LeetCode 530. 二叉搜索树的最小绝对差:两种解法详解(迭代+递归)
前端·算法·typescript
掘金一周5 小时前
2026 春晚魔术大揭秘:作为程序员,分分钟复刻一个 | 掘金一周 2.26
前端·人工智能·后端
兴芳6 小时前
Tencent Cloud Captcha
前端
一个假的前端男6 小时前
# 从零开始创建 Flutter Web 项目(附 VS Code 插件推荐)
前端·flutter·react.js
卸任6 小时前
Windows判断是笔记本还是台式
前端·react.js·electron