0
点赞
收藏
分享

微信扫一扫

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

腊梅5朵 2024-08-01 阅读 14
前端vue.js

选择式写法

一、安装pinia依赖

终端输入:npm install pinia
在这里插入图片描述

二、配置pinia

第一步:创建仓库,在src目录下创建文件夹modules和文件index.ts.
在这里插入图片描述第二步:配置index.ts

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

第三步:在main.ts引入

在这里插入图片描述第四步(案例):配置小仓库info

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;

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

在这里插入图片描述

组合式写法

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;
举报

相关推荐

0 条评论