Pinia 的基本用法介绍

260 阅读1分钟

pinia 的用法很简单,个人感觉比vuex 还简单

1. 安装 pinia

pnpm install pinia

// main.ts
import { createPinia } from 'pinia';
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
app.use(createPinia()) // 挂载pinia

2. defineStore 定义(Hooks)

// pinia/index.ts
import { defineStore } from 'pinia'
export const useLyonStore = defineStore('storeId1', {
  state: () => {
    return {
      lyon: 'xxxxx',
      count: 0
    }
  },
  getters: { // computed 属性
    getCount(state) {
      return state.count
    },
    getLyon(state) {
      return state.lyon
    }
  },
  actions: { // 同步 | 异步都可以定义
    fetchFn(): void {
      setTimeout(() =>{
        console.log("fetchFn", this)
      }, 1000)
      this.increment()
    },
    increment() {
      console.log(2222)
      this.count++
    }
  }
})

// 组件中渲染
import { useLyonStore } from '../pinia'; // 引入hook
const store = useLyonStore() // 这里就是hook 方式

// template 中渲染
<div>{{ store.lyon }}</div>
<div>{{ store.count }}</div>

<button @click="store.increment">同步触发</button>
<button @click="store.fetchFn">异步触发</button>
<button @click="store.$reset">点击重置为state 默认值</button>

3. $reset() | $subscribe | $onAction 等Api 用法

// store.$reset()
<button @click="store.$reset">点击重置为state 默认值</button> 
或者 store.$reset() 触发

/ 监听所有 pinia - hook方法 
store.$subscribe((args, state) => {
  console.log('args====', args)
  console.log('state------', state)
}, {
  detached: true // 第二参数 设置组件销毁后是否继续监听
})
// 监听所有 pinia - action方法
store.$onAction((args:any) => {
  console.log('args====', args)
  args.after(() => { 
    // 触发后 进行一些逻辑
    console.log('after')
  })
  args.onError(() => {
    // 捕获一些差错
    console.log('onError')
  })
  console.log('action')
}, true) // 第二个参数 设置组件销毁后是否继续监听
})