vue3+vuex4+pinia+typescript实现token的
时间: 2023-09-02 09:07:43 浏览: 115
实现 token 的方法,可以参考下面的代码实现:
在 `src/store` 目录下新建 `auth` 目录,用于存放认证相关的代码。
```typescript
// src/store/auth/state.ts
export interface AuthState {
token: string | null;
}
export const state: AuthState = {
token: localStorage.getItem('token') || null,
};
```
```typescript
// src/store/auth/mutations.ts
import { AuthState } from './state';
export const mutations = {
setToken(state: AuthState, token: string) {
state.token = token;
localStorage.setItem('token', token);
},
clearToken(state: AuthState) {
state.token = null;
localStorage.removeItem('token');
},
};
```
```typescript
// src/store/auth/actions.ts
import { ActionContext } from 'vuex';
import { AuthState } from './state';
import { RootState } from '../root-state';
export const actions = {
async login(context: ActionContext<AuthState, RootState>, payload: { username: string; password: string }) {
// 发送登录请求
const response = await fetch('/api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
});
if (response.ok) {
const { token } = await response.json();
context.commit('setToken', token);
} else {
throw new Error('登录失败');
}
},
logout(context: ActionContext<AuthState, RootState>) {
context.commit('clearToken');
},
};
```
```typescript
// src/store/auth/index.ts
import { Module } from 'vuex';
import { AuthState, state } from './state';
import { mutations } from './mutations';
import { actions } from './actions';
import { RootState } from '../root-state';
export const auth: Module<AuthState, RootState> = {
namespaced: true,
state,
mutations,
actions,
};
```
然后,在 `src/store` 目录下新建 `index.ts` 文件,用于创建 store 实例。
```typescript
// src/store/index.ts
import { createStore } from 'vuex';
import { auth } from './auth';
import { RootState } from './root-state';
export const store = createStore<RootState>({
modules: {
auth,
},
});
```
最后,在 `main.ts` 中引入 store 实例,并在根组件中注入。
```typescript
// main.ts
import { createApp } from 'vue';
import App from './App.vue';
import { store } from './store';
const app = createApp(App);
app.use(store);
app.mount('#app');
```
这样,就可以在组件中通过 `this.$store.state.auth.token` 访问 token 了。在登录成功后,通过 `this.$store.dispatch('auth/login', { username, password })` 更新 token;在注销时,通过 `this.$store.dispatch('auth/logout')` 清除 token。
阅读全文