Ricerca nel sito web

typescript - Come usare un array definito nello store di Pinia?


Ho creato un negozio per usare la risorsa User, e quel negozio ha un array di ruoli. Quello che sto cercando di fare è cercare un ruolo specifico in quell'array. Ho provato a usare le funzioni degli array, ma non funzionano con PropType<T[]>.

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??
        }
    }
});

Sto usando Vue3 con Composition API e Typescript.

Risposta n. 1

Bene, restituisci un oggetto, i cui valori hanno tipi invece di valori effettivi. Puoi provare questo impostando valori di default

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

Oppure puoi usare un interface con valori predefiniti null:

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

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