Nuxt来做一个WordPress服务端渲染的项目,使用axios封装的方式,我们来获取一个用户的token
。
安装JWT来制作WordPress鉴权
安装JWT Authentication for WP REST API,需要详细阅读插件页面的文档来安装。
状态管理
yarn add pinia @pinia/nuxt
nuxt.config.ts
新增@pinia/nuxt
modules: ["@element-plus/nuxt", "@pinia/nuxt"],
新建状态管理文件store/auth.js
// store/auth.js
import { defineStore } from "pinia";
import { post } from "~/server/api/request";
export const useAuthStore = defineStore({
id: "auth",
state: () => ({
token: null,
user: null
}),
actions: {
async login(username, password) {
const response = await post("/jwt-auth/v1/token", { username, password });
this.setToken(response.token);
this.setUser(response);
},
setToken(token) {
this.token = token;
},
setUser(user) {
this.user = user;
}
}
});
制作登录页面
登录时去状态管理调用登录方法,把结果放入token
和user
中。
<template>
<div>
<el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="120px" class="demo-ruleForm">
<el-form-item label="username" prop="username">
<el-input v-model="ruleForm.username" type="text" autocomplete="off" />
</el-form-item>
<el-form-item label="password" prop="password">
<el-input v-model="ruleForm.password" type="password" autocomplete="off" />
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm(ruleFormRef)">Submit</el-button>
<el-button @click="resetForm(ruleFormRef)">Reset</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { useAuthStore } from '~/store/auth'
const router = useRouter();
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
username: '',
password: '',
})
const rules = reactive<FormRules>({
username: [],
password: [],
})
const submitForm = (formEl: FormInstance | undefined) => {
if (!formEl) return
formEl.validate((valid) => {
if (valid) {
if (!useAuthStore().token) {
useAuthStore().login(ruleForm.username, ruleForm.password)
router.push({ path: "/" });
}
} else {
console.log('error submit!')
return false
}
})
}
const resetForm = (formEl: FormInstance | undefined) => {
if (!formEl) return
formEl.resetFields()
}
definePageMeta({
layout: 'custom'
})
</script>
文章版权归 有个狸 所有,未经许可不得转载,责任编辑:有个狸。