pinia action和getter

import {defineStore} from 'pinia'
import {StoreName} from './store-name'
// StoreName是id,用于区分不同的store,自定义即可
export const useStore = defineStore(StoreName.Test, {
  state: () => ({
    count: 0,
    sex: '顶顶顶'
  }),
  // 类似computed,所有都跟vue2差不多
  getters: {
    getNewCount():string {
      return `这是新的${this.count}`
    }
  },
  // 可以写异步和同步方法
  actions: {
    async asyncIncrement() {
      await new Promise((resolve) => {
        setTimeout(() => {
          resolve(this.count++)
        }, 1000)
      })
    },
    increment() {
      this.count++
    },
    // 不可以写箭头函数,否则指向不正确
    updataCount(count: number) {
      this.count = count
    }
  },
})

 

posted on 2025-02-22 15:31  ChoZ  阅读(21)  评论(0)    收藏  举报

导航