Pinia重要整理

37 阅读1分钟
import {defineStore} from pinia
// 对象写法
export const userInfoStore = defineStore('userInfo',{
state: ()=>({count:0, name: 'Eduardo'}) //data数据
getters:{
doubleCount:(state) => state.count * 2 // 计算属性 computed
}
actions:{
increment(){
this.count++ 
} // 方法methods
}
})
// 函数式写法
export const useInfoStore = defineStore('userInfo', ()=>{
    const count = ref(0)
    const name = ref('eduardo')
    const doubleCount = computed(()=>count.value*2)
    function increment(){
    count.value++
    }
    return {count, name, doubleCount, increment}
})
必须return state的所有属性。

使用
import { userInfoStore } from '@/stores/counter'
// 获取实例
const userinfoStore = userInfoStore()