pinia使用

//定义一个名为 loginStore 的store
export const useLoginStore = defineStore('loginStore', {
    state: ()=> {
        return {
            logined: false,
        }
    },
    getters: {
        isLogined: state => state.logined,
    },
    actions: {
        changeLoginStatus(logined: boolean){
            this.logined = logined;
            if(!logined){
                this.authInfo = null;
            }
        }
    }
})
//页面拿到名为 useCounterStore 的store
    const counter = useCounterStore()
    //这边是直接在引用页面修改
    counter.$patch({ count: counter.count + 1 })
    //or
    counter.$patch((state) => {
       counter.count ++
    })
  
    //这边是在store中定义action方法,然后在页面中调用
    counter.increment()

数据响应式写法

doubleValue: computed(() => store.doubleCount),

当仅想要从store中提取响应式属性但是并不会调用任何操作时,可以用 storeToRefs

import { storeToRefs } from 'pinia'

const mainStore = useMainStore()
const { showCenter } = storeToRefs(mainStore)

重置数据

store.$reset()

通过给getter返回一个函数来传递参数(这种情况下getter不会缓存)

//store 中
export const useStore = defineStore('main', {
  getters: {
    getUserById: (state) => {
      return (userId) => state.users.find((user) => user.id === userId)
    },
  },
})

页面使用

const store = useStore()
return { getUserById: store.getUserById }

如果想缓存,可以在getter内部函数中缓存,这种情况下不多见,但是性能应该更高

getActiveUserById(state) {
    const activeUsers = state.users.filter((user) => user.active)
    return (userId) => activeUsers.find((user) => user.id === userId)
},

可以在getter内部使用其他store中的数据

actions 可以是异步的

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值