pinia的基本使用

文章目录


一、基本使用

在这里插入图片描述

在这里插入图片描述

//index.ts
import {defineStore} from 'pinia'
//1.定义并导出容器
//参数1:容器的ID必须唯一,将来pinia会把所有的容器挂载到根容器
//参数2:选项对象
//返回值:一个函数,调用得到容器实例
export const useMainStore = defineStore('main',{
    //类似于组件的data,用来存储全局状态
    //1.必须是函数:为了在服务端渲染时避免交叉请求导致的数据状态污染
    //2.必须是箭头函数,为了更好的ts类型推导
    state:()=>{
        return{
            count:100,
            foo:'bar',
            arr:[1,2,3]
        }
    },
    //类似于组件的computed,用来封装计算属性,有缓存的功能
    getters:{
        //函数接收一个可选参数state状态对象
        count10(state){
            console.log('count10调用了');
            return state.count + 10
            
        }
    },
    //类似于组件的methods,封装业务逻辑,修改state
    actions:{
        // 注意:不能使用箭头函数定义action,因为箭头函数绑定外部this
        changeState(num: number){
            this.count += num
            this.foo = 'hhh'
            this.arr.push(5)
        }
    }
})
//HelloWorld.vue
<template>
  <p>{{ count }}</p>
  <p>{{ foo }}</p>
  <p>{{mainStore.arr}}</p>
  <p>{{mainStore.count10}}</p>
  <p>{{mainStore.count10}}</p>
  <hr />
  <p>
    <button @click="handleChangeState">修改数据</button>
  </p>
</template>

<script lang="ts" setup>
import { storeToRefs } from "pinia";
import { useMainStore } from "../store/index";

const mainStore = useMainStore();

console.log(mainStore.count);

//这样拿到的数据不是响应式的
// const {count,foo} = mainStore
//解决方法:把解构出来的数据做ref响应式代理
const { count, foo } = storeToRefs(mainStore);

console.log(count.value);

//修改数据
const handleChangeState = () => {
  //方式一:
  // mainStore.count++;
  // mainStore.foo = 'hello'
  //方式二:修改多个数据建议使用$patch批量更新
  // mainStore.$patch({
  //   count:mainStore.count + 1,
  //   foo:'hello',
  //   arr:[...mainStore.arr,4]
  // })
  //方式三:更好的批量更新方式:$patch一个函数
  // mainStore.$patch(state=>{
  //   state.count++
  //   state.foo = 'hello'
  //   state.arr.push(4)
  // })
  //方式四:逻辑较多的时候可以封装到actions做处理
  mainStore.changeState(10)
};
</script>

<style>
</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值