Pinia从安装到使用

什么是Pinia

添加Pinia到vue项目

使用Pinia实现计数器案例

counter.js

import {defineStore} from "pinia";
import {ref} from "vue";

export const useCounterStore = defineStore('coutner',()=>{
    //定义数据(state)
    const count = ref(0)

    //定义修改数据的方法(action同步+异步)
    const add = ()=>{
        count.value++
    }

    //以对象的形式return供组件使用
    return {count,add}
})

App.vue

<script setup>
import {computed, provide, ref, watch} from "vue";
import Son from './components/Son.vue';
import {useCounterStore} from "./stores/counter";
//导入

//执行方法得到useCounterStore的实例对象,实例化
const counterStore = useCounterStore()

</script>

<template>
  <div>
    <button @click="counterStore.add">{{counterStore.count}}</button>
  </div>
</template>

getter和异步action

storeToRefs

storeToRefs 是 Pinia 提供的一个实用函数,用于将 store 中的状态转换为响应式引用(reactive refs)。这使得在 Vue 组件中使用 Pinia 的状态更加方便,尤其是在组合式 API 中。

为什么使用 storeToRefs?

在组合式 API 中,直接从 store 中解构状态可能会导致失去响应性。使用 storeToRefs 可以确保我们解构出来的每个状态仍然是响应式的。

需要注意的是,要区分一下,解构数据和解构方法是不一样的

解构数据需要加上storeToRefs(否则会失去响应性),解构方法则不需要担心。

<script setup>
import {computed, provide, ref, watch} from "vue";
import Son from './components/Son.vue';
import {useCounterStore} from "./stores/counter";
import {storeToRefs} from "pinia";
//导入

//执行方法得到useCounterStore的实例对象,实例化
const counterStore = useCounterStore()
const {add} = counterStore
const {count} = storeToRefs(counterStore)
</script>

<template>
  <div>
    <button @click="add">{{count}}</button>
  </div>
</template>

总结

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值