pinia的基本使用,从入门到精通

一、 安装

yarn add pinia
# 或者使用 npm
npm install pinia

二、 main.ts 中引入注册

import { createApp } from 'vue' 
import App from './App.vue'
import {createPinia} from "pinia"  // 1. 引入
const app = createApp(App)
const pinia = createPinia()  // 2. 创建
app.use(pinia)  // 3. 注册
app.mount('#app')

三、 src下创建store文件夹,文件夹中存放ts文件每个小仓库

这里我创建一个count.ts

import {defineStore} from "pinia"
import {ref,computed} from "vue";
// 组合式写法
export const useCountStore = defineStore("count",()=>{
    // 数据,相当于state
    const num = ref(5)
    const name = ref("狗子")
    
    // 计算属性,相当于getters
    const getName = computed(():string=>{
        return name.value += "!"
    })
    const getNum = computed(():number=>{
        return num.value * 10
    })
    
    // 方法,相当于actions
    function increment(newValue: number):void{
        num.value+=newValue
    }
    
    // 最后必须return,否侧外界拿不到
    return {
        num,
        name,
        increment,
        getNum,
        getName
    }
})

count.ts 还有一种选项式写法

import {defineStore} from "pinia"

// 选项式写法
export const useCountStore = defineStore("count",{
    state() {
        return{
            num:5,
            name:"狗子"
        }
    },
    actions:{
        increment(newValue: number):void{
            this.num+=newValue
        },
    },
    getters:{
        getNum(state){
            return state.num * 10
        },
        getName(state){
            return state.name += "!"
        }
    }
})

四、组件中读取与修改数据

1. 读取数据,可直接读取

<script setup lang="ts">
import {useCountStore} from "@/store/count"

const countStore = useCountStore()

console.log(countStore.num)  // 5


</script>

2. 修改数据的三种方式

// 第一种:改一个
  countStore.num += 1
  
// 第二种:$patch 改多个
countStore.$patch({
  num: ++countStore.num,
  name: countStore.name+="~",
})

// 第三种:还记得count.ts中定义的方法吗,这就用上了
 countStore.increment(5);

五、storeToRefs:用于解构出的数据依然保持响应式

<script setup lang="ts">
import {useCountStore} from "@/store/count"
import {storeToRefs} from "pinia"

const countStore = useCountStore()

// 是响应式数据
const {num, name,getNum,getName} = storeToRefs(countStore)

// 不是响应式数据
const {num, name,getNum,getName} = countStore

</script>

<template>
  <div class="count">
       解构有啥用?答:读取数据更方便
       不解构:{{ countStore.num }}
       解构:{{ num }}
  </div>
</template>

六、监听仓库中的数据发生改变:$subscribe

mutate:包含修改的方式与发生变化的值等等

state:包含仓库中的数据

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值