【Vue3】状态管理工具——pinia的使用

目录

搭建pinia环境

存储数据

组件中使用数据

修改数据

storeToRefs

$subscribe


pinia相当于vue2中的vuex,pinia也是vue.js状态管理库。

搭建pinia环境

下载

npm install pinia

创建

src/main.js

import { createApp } from 'vue'
import App from './App.vue'
 
/* 引入createPinia,用于创建pinia */
import { createPinia } from 'pinia'
 
/* 创建pinia */
const pinia = createPinia()
const app = createApp(App)
 
/* 使用插件 */
app.use(pinia)
app.mount('#app')

存储数据

它有三个概念:store、getters、actions,相当于组件中的data、computed和methods。

src/store/count.js

// 引入defineStore用于创建store
import {defineStore} from 'pinia'
 
// 定义并暴露一个store
export const useCountStore = defineStore('count',{
  // 动作
  actions:{
    increment(value) {
      this.sum += value
    }
  },
  // 状态
  state(){
    return {
      sum:6,
      a:1,
      b:2,
      c:3
    }
  },
  // 计算
  getters:{
    bigSum:(state) => state.sum *10,
  }
})

actions中可以通过this来获取到state中的数据,getters用于处理state中的数据。

组件中使用数据

<template>
  <h2>state中的数据:{{ countStore.sum }}</h2>
  <h2>getters处理的数据:{{ countStore.bigSum }}</h2>
  <button @click="add">点击加三</button>
</template>
 
<script setup name="Count">
  // 引入对应的useXxxxxStore	
  import {useCountStore} from '@/store/count'
  
  // 调用useXxxxxStore得到对应的store
  const countStore = useCountStore()
 
  const add = () => {
    //调用actions中的方法
    countStore.increment(3)
  }
</script>

修改数据

(1)直接修改

countStore.sum = 666

(2)批量修改

countStore.$patch({
  sum:999,
  a:11,
  b:22,
  c:33
})

(3)通过actions修改,然后在组件中调用actions中的方法

storeToRefs

使用storeToRefs可以将store中的数据转换成ref对象。

注意:pinia中的storeToRefs只会对数据本身转换,而vue中的toRef会转换store中的数据。

我们通过解构拿到的数据不是响应式的,所以需要使用storeToRefs将它们变成响应式的。

<template>
	<div class="count">
		<h2>当前求和为:{{sum}}</h2>
	</div>
</template>
 
<script setup lang="ts" name="Count">
  import { useCountStore } from '@/store/count'
  /* 引入storeToRefs */
  import { storeToRefs } from 'pinia'
 
	/* 得到countStore */
  const countStore = useCountStore()
  /* 使用storeToRefs转换countStore,随后解构 */
  const {sum} = storeToRefs(countStore)
</script>

$subscribe

使用$subscribe方法可以侦听store中的数据变化

countStore.$subscribe((mutate,state)=>{
  console.log(mutate, state);
})

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值