安装vue-router
pnpm install vue-router
创建router
src下新增router目录,ruoter目录中新增index.ts
import { createRouter, createWebHashHistory } from "vue-router";
const routes = [
{
path: "/",
name: "Home",
component: () => import("@/views/home/index.vue"),
},
{
path: "/register",
name: "Register",
component: () => import("@/views/register/index.vue"),
}
];
const router = createRouter({
history: createWebHashHistory(),
routes,
});
export default router;
创建首页
src下新增views目录,views目录下新增home目录,home目录下新增index.vue文件
<template>
<div>
this is home page
</div>
<div class="txt-r">
<router-link to="/register">没有账号?去注册</router-link>
</div>
</template>
创建注册页
views目录下新增register目录,register目录下新增index.vue文件
<template>
<div>
<el-form :model="user" label-width="86px">
<h3 class="title">系统注册</h3>
<el-form-item label="用户名" prop="username">
<el-input v-model="user.username" placeholder="请输入用户名" prefix-icon="user"></el-input>
</el-form-item>
<el-form-item label="邮箱" prop="email">
<el-input v-model="user.email" placeholder="请输入邮箱" prefix-icon="message"></el-input>
</el-form-item>
<el-form-item label="密码" prop="password">
<el-input v-model="user.password" type="password" placeholder="请输入密码" prefix-icon="lock"></el-input>
</el-form-item>
<el-form-item label>
<el-button type="primary" @click="doRegister">注册</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script setup lang="ts">
import { useRouter } from 'vue-router';
import { register } from '@/api';
import { ref } from 'vue'
import type { User } from '@/types';
const router = useRouter();
const user = ref<User>({
email: '',
username: '',
password: ''
});
const doRegister = async () => {
try {
const res = await register({ user: user.value });
console.log(res.data.user);
router.push({ name: 'Home' });
} catch (error) {
}
}
</script>
main.ts引入router对象
修改App.vue
<template>
<router-view></router-view>
</template>
运行测试
点击 去注册
表单校验
修改register/index.vue