自用笔记——pinia使用记录

58 阅读1分钟

pinia中没有mutation,他只有state,getters,action

pinia中d的action支持同步和异步两种

安装

npm install pinia

导入

---main.js
import {createPinia } from 'pinia'
app.use(createPinia())

创建

src下创建store/counterStroe.js 同步异步方法都写在actions就好了

import { defineStore } from 'pinia'

const useCounterStore =defineStore('counterStore', {
    state() {
        return {
            count: 0
        }
    },
     actions:{
         add(){
             this.count++
         }
     }
})
export default useCounterStore

使用

import useCounterStore from '../../src/store/counterStore'
import {storeToRefs} from 'pinia'
const counterStore=useCounterStore()
const {count} = storeToRefs(counterStore)    //解构,可有可无,看喜好
<div class="home">
    {{count}}                               //解构后的情况,直接使用
    {{counterStore.count}}                  //未解构的情况
    <button @click="counterStore.add()">加</button>      //解构了也没有用,只能这样用
</div>