網站搜尋

typescript - 如何使用在 Pinia 商店中定義的陣列?


我創建了一個存儲以便使用 User 資源,該存儲有一個角色陣列。我想做的是在該陣列中搜尋特定的角色。我嘗試使用陣列函數,但它無法與 PropType 一起使用。

import router from "@/router";
import axios from 'axios';
import { defineStore } from "pinia";
import { PropType } from "vue";
import { ApplicationConstants } from '../utils/Constants';

type Role = {
    name: string;
}

export const useUserStore = defineStore('user', {
    state: () => ({
        currentUserId: Number,
        currentUserUsername: String,
        currentUserRoles: Array as PropType<Role[]>,
        isLoggedIn: false
    }),
    getters: {
        getCurrentUserId: (state) => state.currentUserId,
        getCurrentUsername: (state) => state.currentUserUsername,
        getCurrentUserRoles: (state) => state.currentUserRoles,
        isUserLoggedIn: (state) => state.isLoggedIn,
        // hasCurrentUserRole: (state) => { return (role: String | Role) ????} 
    },
    actions: {
        logIn(username: string, password: string) {
            const authDTO = {
                "username" : username,
                "password" : password
                }
                const loginResponse = axios({
                    method: 'post',
                    url: ApplicationConstants.API_LOGIN_URL,
                    data: authDTO
                }).then((loginResponse) => {
                    /** Set JWT access token in LocalStorage. */
                    const token = loginResponse.headers["access-token"];
                    localStorage.setItem("accessToken", token);
                    /** Set current user credentials. */
                    this.currentUserId = loginResponse.data.id;
                    this.currentUserUsername = loginResponse.data.username;
                    this.currentUserRoles = loginResponse.data.roles;
                    this.isLoggedIn = true;
                    /** Go to Home page. */
                    console.log("inside login in userstore");
                    router.push("/");
                }).catch((error) => {
                    
                });
        },
        logOut() {
            this.$reset();
            this.isLoggedIn = false;
            router.push("/login");
        },
        containsRole (roleName: String | Role)  {
            // how??
        }
    }
});

我正在使用 Vue3 搭配 Composition API 和 Typescript。

答案#1

你返回了一個物件,其值有類型而不是實際值。你可以透過設定預設值來嘗試這個方法。

state: () => ({
    currentUserId: 0,
    currentUserUsername: "",
    currentUserRoles: [] as Role[],
    isLoggedIn: false
}),

或者你可以使用帶有 null 預設值的 interface:

state: (): StoreStateI => ({
    currentUserId: null,
    currentUserUsername: null,
    currentUserRoles: [],
    isLoggedIn: false
}),

interface StoreStateI {
   currentUserId: null | number
   currentUserUsername: null | string
   currentUserRoles: Role[]
   isLoggedIn: boolean
}