Dav*_*ghe 2 typescript vue.js pinia
我创建了一个商店来使用用户资源,并且该商店具有一系列角色。我想做的是搜索该数组中的特定角色。我尝试使用数组函数,但它不适用于 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??
}
}
});
Run Code Online (Sandbox Code Playgroud)
我正在使用带有 Composition API 的 Vue3 和 Typescript。
好吧,您返回一个对象,您的值具有类型而不是实际值。您可以通过设置默认值来尝试此操作
state: () => ({
currentUserId: 0,
currentUserUsername: "",
currentUserRoles: [] as Role[],
isLoggedIn: false
}),
Run Code Online (Sandbox Code Playgroud)
或者您可以使用interface带有null默认值的:
state: (): StoreStateI => ({
currentUserId: null,
currentUserUsername: null,
currentUserRoles: [],
isLoggedIn: false
}),
interface StoreStateI {
currentUserId: null | number
currentUserUsername: null | string
currentUserRoles: Role[]
isLoggedIn: boolean
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9780 次 |
| 最近记录: |