pinia 基础用法

Pinia 是一个基于 Vue3 的状态管理库,它提供了简单且强大的方法来管理应用程序的状态。

一、安装 Pinia

npm install pinia

二、注册 Pinia Store

我们需要在应用程序的入口文件中注册 Pinia Store,以便它能够在整个应用程序中使用。

// main.js
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';

const app = createApp(App);
const pinia = createPinia();

app.use(pinia);

app.mount('#app');


三、创建 Pinia Store

接下来,我们需要创建一个 Pinia Store 来管理应用程序的状态。

// index.js
import { createStore } from 'pinia';

export const useCounterStore = createStore('counter',{
  state: () => {
	return {
	  count: 0,
  	}
  },
  actions: {
    increment() {
      this.count++;
    },
    decrement() {
      this.count--;
    },
  },
});

在上面createStore函数中,第一个参数是id,用于区别部分不同的store,当然你也可以将id用枚举方式保存,避免重复造成不必要的麻烦

//enum/index.ts    用于存储store中的id值
export const enum storeId {
  COUNTER = "counter",
}


// store/index.js
import { defineStore } from "pinia";
import { storeId } from "@/enum/index";

export const useCounterStore = defineStore(storeId.COUNTER, {
  state: () => {
    return {
      count: 0
    }
  },
   getters: {
    double: (state) => state.count * 2,
  },
  actions: {
    increment() {
      this.count++;
    },
    decrement() {
      this.count--;
    },
  },
});

actions中存放我们的逻辑代码,如接口请求等。


四、使用 Pinia Store

获取store中的值,下面这五种方法都可以获取到

<template>
  <div>
    <button @click="increment">增加</button>
    <button @click="decrement">减少</button>

    {{ Count.count }}
  </div>
</template>
<script setup lang="ts">
import { useCounterStore } from "@/store/index";

const Count = useCounterStore();
const increment = () => {

  //1
  Count.count++;    

  //2
  Count.$patch({
    count: Count.count + 1,
  });

  //3
  Count.$patch(() => {
    Count.count += 2;
  });

  //4
  Count.increment();
};

const decrement = () => {
  Count.count--;
};
</script>

<style scoped lang="scss">
</style>

在上面四种方法可以看出,Pinia简化了操作,获取和设置值更加简单。
但Pinia直接解构值没有响应效果,这需要我们借助它的storeToRefs 方法转为ref模式,如下:

import { storeToRefs } from "pinia";
import { useCounterStore } from "@/store/index";

const Count = useCounterStore();
let { count } = storeToRefs(Count);
const increment = () => {

  //5
  count.value++;
};

上面只是本人学习pinia后做的简单总结,更多方法请参考pinia官网

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值