二、Vue3全局状态管理工具pinia仓库初始化

第一步:在src目录下新建store文件夹,store下面创建一个index.ts文件,定义仓库Store

src/store/index.ts中引入defineStore;

import { defineStore } from 'pinia';

存储是使用定义的defineStore(),并且它需要一个唯一的名称,作为第一个参数传递

我们将名称抽离出去,store文件夹下新建文件store-namespace/index.ts

export const enum Names {
    Test = 'TEST'
}

在src/store/index.ts中引入store-namespace/index.ts

import { defineStore } from 'pinia';
import { Names } from './store-name';
// 这个名称,也称为id,是必要的,Pania 使用它来将商店连接到 devtools。
// 将返回的函数命名为use...是可组合项之间的约定,以使其使用习惯。
export const useTestStore = defineStore(Names.Test, {

});

第二步:定义值

import { defineStore } from 'pinia';
import { Names } from './store-name';
// 这个名称,也称为id,是必要的,Pania 使用它来将商店连接到 devtools。
// 将返回的函数命名为use...是可组合项之间的约定,以使其使用习惯。
export const useTestStore = defineStore(Names.Test, {
    state:()=>{
        return {
            current:1111,
            name: '张三'
        }
    },
    getters:{ // 类似computed计算属性 同样有缓存的

    },
    actions:{ // 类似 methods方法 可以做同步、异步操作 提交state

    }
});

第三步:在页面中取值

<template>
  <header>
    <div>
      pinia: {{ Test.current }} --- {{ Test.name }}
    </div>
  </header>

  <RouterView />
</template>
<script setup lang="ts">
// 引入store
import {useTestStore} from './store';
// 调用这个hooks函数
const Test = useTestStore();
</script>
<style scoped>
</style>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值