五、Vue3中使用Pinia的同步异步操作及getters用法

Pinia的同步操作

src/store/index.ts

import { defineStore } from 'pinia';
import { Names } from './store-name';
type User = {
    name: string,
    age: number
}
const result:User = {
    name: '白素贞',
    age: 999
}
export const useTestStore = defineStore(Names.Test, {
    state:()=>{
        return {
            user: {}
        }
    },
    getters:{ // 类似computed计算属性 同样有缓存的

    },
    actions:{ // 
        setUser(){ // 同步操作 注意此处不要写箭头函数,否则this指向就不对了
            this.user = result;
        }
    }
});

src/store/store-name.ts

export const enum Names {
    Test = 'TEST'
}

组件调用


 

 

Pinia的异步操作

src/store/index.ts

import { defineStore } from 'pinia'
import { Names } from './store-name'
type Result = {
    name: string
    age: number
}
const Login = (): Promise => {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve({
                name: '小青',
                age: 999
            })
        }, 3000)
    })
}
export const useTestStore = defineStore(Names.TEST, {
    state: () => ({
        user: {}
    }),
    actions: {
        async getLoginInfo() { // 异步操作
            const result = await Login()
            this.user = result;
        }
    },
})

组件调用




getters用法

import { defineStore } from 'pinia';
import { Names } from './store-name';
export const useTestStore = defineStore(Names.TEST, {
    state:()=>{
        return {
            name: "小飞机"
        }
    },
    getters:{ // 类似computed计算属性 同样有缓存的
        newName():string{
            return `$-${this.name}`
        }
    },
    actions:{ // 
        setUser(){
            this.name = '坦克';
        }
    }
});

使用




你可能感兴趣的:(vue.js入门,前端,javascript,开发语言)