您现在的位置是:首页 > 编程语言学习 > 前端编程语言 > 文章正文 前端编程语言

SpringBoot和Vue.js实现的前后端分离的用户权限管理系统

2023-04-03 17:50:37 前端编程语言

简介后端实现1. 数据库设计我们需要设计两个表:用户表和角色表。用户表字段类型描述idbigint(20)用户IDusernamevarchar(50)用户名passwordvar...

后端实现

1. 数据库设计

我们需要设计两个表:用户表和角色表。

用户表

  1. 字段 类型 描述 
  2. id bigint(20) 用户 ID 
  3. username varchar(50) 用户名 
  4. password varchar(255) 密码 
  5. email varchar(50) 邮箱 
  6. phone varchar(20) 手机号码 
  7. create_by varchar(50) 创建人 
  8. create_time datetime 创建时间 
  9. update_by varchar(50) 最后修改人 
  10. update_time datetime 最后修改时间 
  11. status tinyint(1) 用户状态 

角色表

  1. 字段 类型 描述 
  2. id bigint(20) 角色 ID 
  3. role_name varchar(50) 角色名称 
  4. create_by varchar(50) 创建人 
  5. create_time datetime 创建时间 
  6. update_by varchar(50) 最后修改人 
  7. update_time datetime 最后修改时间 
  8. status tinyint(1) 角色状态 

用户角色表

  1. 字段 类型 描述 
  2. id bigint(20) ID 
  3. user_id bigint(20) 用户 ID 
  4. role_id bigint(20) 角色 ID 
  5. create_by varchar(50) 创建人 
  6. create_time datetime 创建时间 
  7. update_by varchar(50) 最后修改人 
  8. update_time datetime 最后修改时间 
  9. status tinyint(1) 状态 

2. 创建 Maven 项目

使用 Maven 创建 Spring Boot 项目,引入 Spring Boot Web、Spring Boot JPA、MySQL 和 Lombok 等依赖。可以使用以下命令创建 Maven 项目:


  1. mvn archetype:generate -DgroupId=com.example -DartifactId=user-management -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false 

3. 配置数据库

在 application.properties 文件中添加以下配置:

  1. spring.datasource.url=jdbc:mysql://localhost:3306/user_management?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai 
  2. spring.datasource.username=root 
  3. spring.datasource.password=root 
  4. spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver 
  5.  
  6. spring.jpa.hibernate.ddl-auto=update 
  7. spring.jpa.properties.hibernate.show_sql=true 
  8. spring.jpa.properties.hibernate.format_sql=true 
  9. spring.jpa.properties.hibernate.use_sql_comments=true 

4. 创建实体类

创建 User、Role 和 UserRole 实体类,使用 Lombok 注解简化代码。具体代码如下:

User.java

  1. @Data 
  2. @Entity 
  3. @Table(name = "user"
  4. public class User { 
  5.     @Id 
  6.     @GeneratedValue(strategy = GenerationType.IDENTITY) 
  7.     private Long id 
  8. User.java(续) 
  9. java 
  10. Copy code 
  11.     private String username; 
  12.     private String password; 
  13.     private String email; 
  14.     private String phone; 
  15.     private String createBy; 
  16.     private Date createTime; 
  17.     private String updateBy; 
  18.     private Date updateTime; 
  19.     private Boolean status; 

Role.java

  1. @Data 
  2. @Entity 
  3. @Table(name = "role"
  4. public class Role { 
  5.     @Id 
  6.     @GeneratedValue(strategy = GenerationType.IDENTITY) 
  7.     private Long id; 
  8.     private String roleName; 
  9.     private String createBy; 
  10.     private Date createTime; 
  11.     private String updateBy; 
  12.     private Date updateTime; 
  13.     private Boolean status; 

UserRole.java

  1. @Data 
  2. @Entity 
  3. @Table(name = "user_role"
  4. public class UserRole { 
  5.     @Id 
  6.     @GeneratedValue(strategy = GenerationType.IDENTITY) 
  7.     private Long id; 
  8.     private Long userId; 
  9.     private Long roleId; 
  10.     private String createBy; 
  11.     private Date createTime; 
  12.     private String updateBy; 
  13.     private Date updateTime; 
  14.     private Boolean status; 

5. 创建 Repository

创建 UserRepository、RoleRepository 和 UserRoleRepository,用于操作数据库。

UserRepository.java

  1. @Repository 
  2. public interface UserRepository extends JpaRepository<User, Long> { 
  3.     User findByUsername(String username); 
  4. RoleRepository.java 
  5. java 
  6. Copy code 
  7. @Repository 
  8. public interface RoleRepository extends JpaRepository<Role, Long> { 
  9. UserRoleRepository.java 
  10. java 
  11. Copy code 
  12. @Repository 
  13. public interface UserRoleRepository extends JpaRepository<UserRole, Long> { 
  14.     List<UserRole> findByUserId(Long userId); 

6. 创建 Service

创建 UserService、RoleService 和 UserRoleService,用于处理业务逻辑。

UserService.java

  1. @Service 
  2. public class UserService { 
  3.     @Autowired 
  4.     private UserRepository userRepository; 
  5.     @Autowired 
  6.     private UserRoleRepository userRoleRepository; 
  7.  
  8.     public User findByUsername(String username) { 
  9.         return userRepository.findByUsername(username); 
  10.     } 
  11.  
  12.     public List<UserRole> findUserRolesByUserId(Long userId) { 
  13.         return userRoleRepository.findByUserId(userId); 
  14.     } 

RoleService.java

  1. @Service 
  2. public class RoleService { 
  3.     @Autowired 
  4.     private RoleRepository roleRepository; 
  5. UserRoleService.java 
  6. java 
  7. Copy code 
  8. @Service 
  9. public class UserRoleService { 
  10.     @Autowired 
  11.     private UserRoleRepository userRoleRepository; 

7. 创建 Controller

创建 UserController、RoleController 和 UserRoleController,用于处理请求。

UserController.java

  1. @RestController 
  2. @RequestMapping("/api/user"
  3. public class UserController { 
  4.     @Autowired 
  5.     private UserService userService; 
  6.  
  7.     @GetMapping("/{username}"
  8.     public User findByUsername(@PathVariable String username) { 
  9.         return userService.findByUsername(username); 
  10.     } 
  11.  
  12.     @GetMapping("/{userId}/roles"
  13.     public List<UserRole> findUserRolesByUserId(@PathVariable Long userId) { 
  14.         return userService.findUserRolesByUserId(userId); 
  15.     } 

RoleController.java

  1. @RestController 
  2. @RequestMapping("/api/role"
  3. public class RoleController { 
  4.     @Autowired 
  5.     private RoleService roleService; 
  6.  
  7.     @GetMapping(""
  8.     public List<Role> findAll() { 
  9.         return roleService.findAll(); 
  10.     } 

UserRoleController.java

  1. @RestController 
  2. @RequestMapping("/api/userRole"
  3. public class UserRoleController { 
  4.     @Autowired 
  5.     private UserRoleService userRoleService; 

8. 启动应用

使用 Maven 命令 mvn spring-boot:run 启动应用,或者直接运行 UserManagementApplication 类。

9. 完整的SecurityConfig.java:

  1. @Configuration 
  2. @EnableWebSecurity 
  3. public class SecurityConfig extends WebSecurityConfigurerAdapter { 
  4.  
  5.     @Autowired 
  6.     private UserDetailsServiceImpl userDetailsService; 
  7.  
  8.     @Autowired 
  9.     private JwtAuthenticationEntryPoint unauthorizedHandler; 
  10.  
  11.     @Bean 
  12.     public JwtAuthenticationFilter jwtAuthenticationFilter() { 
  13.         return new JwtAuthenticationFilter(); 
  14.     } 
  15.  
  16.     @Override 
  17.     public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception { 
  18.         authenticationManagerBuilder 
  19.                 .userDetailsService(userDetailsService) 
  20.                 .passwordEncoder(passwordEncoder()); 
  21.     } 
  22.  
  23.     @Bean(BeanIds.AUTHENTICATION_MANAGER) 
  24.     @Override 
  25.     public AuthenticationManager authenticationManagerBean() throws Exception { 
  26.         return super.authenticationManagerBean(); 
  27.     } 
  28.  
  29.     @Bean 
  30.     public PasswordEncoder passwordEncoder() { 
  31.         return new BCryptPasswordEncoder(); 
  32.     } 
  33.  
  34.     @Override 
  35.     protected void configure(HttpSecurity http) throws Exception { 
  36.         http 
  37.                 .cors() 
  38.                     .and() 
  39.                 .csrf() 
  40.                     .disable() 
  41.                 .exceptionHandling() 
  42.                     .authenticationEntryPoint(unauthorizedHandler) 
  43.                     .and() 
  44.                 .sessionManagement() 
  45.                     .sessionCreationPolicy(SessionCreationPolicy.STATELESS) 
  46.                     .and() 
  47.                 .authorizeRequests() 
  48.                     .antMatchers("/api/auth/**"
  49.                         .permitAll() 
  50.                     .anyRequest() 
  51.                         .authenticated(); 
  52.  
  53.         http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); 
  54.     } 

其中,JwtAuthenticationFilter是前面提到的JWT认证过滤器,UserDetailsServiceImpl是实现了Spring Security的UserDetailsService接口的用户服务类,JwtAuthenticationEntryPoint是未经授权时抛出的异常处理程序。配置类中的configure方法配置了授权规则,访问“/api/auth/**”路径下的接口不需要认证即可访问,其他所有请求都需要认证后才能访问。同时,我们也添加了JWT认证过滤器。

前端实现

1. 创建 Vue.js 项目

使用 Vue CLI 创建项目:


  1. vue create user-management 

2. 添加依赖

在 package.json 中添加以下依赖:

  1.   "dependencies": { 
  2.     "axios""^0.21.1"
  3.     "element-plus""^1.0.2-beta.55"
  4.     "vue""^2.6.12"
  5.     "vue-router""^3.5.1" 
  6.   } 

然后执行 npm install 安装依赖。

3. 配置 Axios

在 src/main.js 中添加以下代码:

  1. import axios from 'axios' 
  2.  
  3. axios.defaults.baseURL = 'http://localhost:8080/api' 
  4.  
  5. Vue.prototype.$http = axios 

4. 创建路由

在 src/router/index.js 中添加以下代码:

  1. import Vue from 'vue' 
  2. import VueRouter from 'vue-router' 
  3. import Home from '../views/Home.vue' 
  4. import Login from '../views/Login.vue' 
  5.  
  6. Vue.use(VueRouter) 
  7.  
  8. const routes = [ 
  9.   { 
  10.     path: '/'
  11.     name: 'Home'
  12.     component: Home 
  13.   }, 
  14.   { 
  15.     path: '/login'
  16.     name: 'Login'
  17.     component: Login 
  18.   } 
  19.  
  20. const router = new VueRouter({ 
  21.   mode: 'history'
  22.   base: process.env.BASE_URL, 
  23.   routes 
  24. }) 
  25.  
  26. export default router 

5. 创建页面

在 src/views 目录下创建以下页面:

Home.vue

  1. <template> 
  2.   <div> 
  3.     <h1>用户管理</h1> 
  4.     <table> 
  5.       <thead> 
  6.         <tr> 
  7.           <th>用户名</th> 
  8.           <th>邮箱</th> 
  9.           <th>手机号码</th> 
  10.           <th>操作</th> 
  11.         </tr> 
  12.       </thead> 
  13.       <tbody> 
  14.         <tr v-for="user in users" :key="user.id"
  15.           <td>{{ user.username }}</td> 
  16.           <td>{{ user.email }}</td> 
  17.           <td>{{ user.phone }}</td> 
  18.           <td> 
  19.             <button @click="editUser(user)">编辑</button> 
  20.             <button @click="deleteUser(user)">删除</button> 
  21.           </td> 
  22.         </tr> 
  23.       </tbody> 
  24.     </table> 
  25.   </div> 
  26. </template> 
  27.  
  28. <script> 
  29. export default { 
  30.   name: 'Home'
  31.   data() { 
  32.     return { 
  33.       users: [] 
  34.     } 
  35.   }, 
  36.   mounted() { 
  37.     this.loadUsers() 
  38.   }, 
  39.   methods: { 
  40.     loadUsers() { 
  41.       this.$http.get('/user'
  42.         .then(response => { 
  43.           this.users = response.data 
  44.         }) 
  45.         .catch(error => { 
  46.           console.log(error) 
  47.         }) 
  48.     }, 
  49.     editUser(user) { 
  50.       console.log(user) 
  51.     }, 
  52.     deleteUser(user) { 
  53.       console.log(user) 
  54.     } 
  55.   } 
  56. </script> 

Login.vue

  1. <template> 
  2.   <div> 
  3.     <h1>登录</h1> 
  4.     <form @submit.prevent="login"
  5.       <div> 
  6.         <label>用户名:</label> 
  7.         <input type="text" v-model="username" /> 
  8.       </div> 
  9.       <div> 
  10.         <label>密码:</label> 
  11.         <input type="password" v-model="password" /> 
  12.       </div> 
  13.       <button type="submit">登录</button> 
  14.     </form> 
  15.   </div> 
  16. </template> 
  17.  
  18. <script> 
  19. export default { 
  20.   name: 'Login'
  21.   data() { 
  22.     return { 
  23.       username: ''
  24.       password: '' 
  25.     } 
  26.   }, 
  27.   methods: { 
  28.     login() { 
  29.       const params = { 
  30.         username: this.username, 
  31.         password: this.password 
  32.   } 
  33.  
  34.   this.$http.post('/login', params) 
  35.     .then(response => { 
  36.       console.log(response) 
  37.     }) 
  38.     .catch(error => { 
  39.       console.log(error) 
  40.     }) 
  41. </script> 

6. 添加 Element UI 组件

在 src/main.js 中添加以下代码:

  1. import ElementPlus from 'element-plus' 
  2. import 'element-plus/dist/index.css' 
  3.  
  4. Vue.use(ElementPlus) 

7. 运行项目

在项目根目录下执行以下命令运行项目:


  1. npm run serve 

然后在浏览器中访问 http://localhost:8080 查看效果。

以上代码只是简单地实现了用户列表的显示以及登录功能的实现,还需要进一步完善和优化。同时,还需要在后端实现相应的接口。

8. 添加路由

在 src/router/index.js 中添加以下代码:

  1. import Vue from 'vue' 
  2. import VueRouter from 'vue-router' 
  3. import Login from '../views/Login.vue' 
  4. import UserList from '../views/UserList.vue' 
  5.  
  6. Vue.use(VueRouter) 
  7.  
  8. const routes = [ 
  9.   { 
  10.     path: '/'
  11.     redirect: '/login' 
  12.   }, 
  13.   { 
  14.     path: '/login'
  15.     name: 'Login'
  16.     component: Login 
  17.   }, 
  18.   { 
  19.     path: '/userlist'
  20.     name: 'UserList'
  21.     component: UserList, 
  22.     meta: { 
  23.       requireAuth: true 
  24.     } 
  25.   } 
  26.  
  27. const router = new VueRouter({ 
  28.   mode: 'history'
  29.   base: process.env.BASE_URL, 
  30.   routes 
  31. }) 
  32.  
  33. export default router 

其中,meta 属性中的 requireAuth 表示该路由需要登录才能访问。

9. 添加登录拦截

在 src/main.js 中添加以下代码:

  1. router.beforeEach((to, from, next) => { 
  2.   if (to.meta.requireAuth && !localStorage.getItem('token')) { 
  3.     next({ 
  4.       path: '/login'
  5.       query: { redirect: to.fullPath } 
  6.     }) 
  7.   } else { 
  8.     next() 
  9.   } 
  10. }) 

这段代码的作用是,在用户访问需要登录才能访问的路由时,检查用户是否已登录。如果用户未登录,则跳转到登录页面,并将目标路由的路径保存到查询参数中,以便用户登录成功后自动跳转到目标路由。

10. 添加用户服务

在 src/services 目录下创建 UserService.js 文件,并添加以下代码:

  1. import axios from 'axios' 
  2.  
  3. const API_URL = '/api/users/' 
  4.  
  5. class UserService { 
  6.   getUsers () { 
  7.     return axios.get(API_URL) 
  8.   } 
  9.  
  10.   getUser (id) { 
  11.     return axios.get(API_URL + id) 
  12.   } 
  13.  
  14.   createUser (data) { 
  15.     return axios.post(API_URL, data) 
  16.   } 
  17.  
  18.   updateUser (id, data) { 
  19.     return axios.put(API_URL + id, data) 
  20.   } 
  21.  
  22.   deleteUser (id) { 
  23.     return axios.delete(API_URL + id) 
  24.   } 
  25. export default new UserService() 

该文件定义了一个 UserService 类,用于向后端发送请求,获取用户数据。其中,API_URL 表示后端 API 的根路径,getUsers、getUser、createUser、updateUser 和 deleteUser 方法分别对应获取用户列表、获取单个用户、创建用户、更新用户和删除用户。

11. 添加用户列表页面

在 src/views 目录下创建 UserList.vue 文件,并添加以下代码:

  1. <template> 
  2.   <div> 
  3.     <h1>用户列表</h1> 
  4.     <div class="mb-3"
  5.       <router-link to="/user/add" class="btn btn-primary">添加用户</router-link> 
  6.     </div> 
  7.     <table class="table table-striped"
  8.       <thead> 
  9.         <tr> 
  10.           <th>用户名</th> 
  11.           <th>邮箱</th> 
  12.           <th>角色</th> 
  13.           <th>操作</th> 
  14.         </tr> 
  15.       </thead> 
  16.       <tbody> 
  17.         <tr v-for="user in userList" :key="user.id"
  18.           <td>{{ user.username }}</td> 
  19.           <td>{{ user.email }}</td> 
  20.           <td>{{ user.roles.map(role => role.name).join(', ') }}</td> 
  21.           <td> 
  22.             <router-link :to="'/user/edit/' + user.id" class="btn btn-primary">编辑</router-link> 
  23.             <button class="btn btn-danger" @click="deleteUser(user.id)">删除</button> 
  24.           </td> 
  25.         </tr> 
  26.       </tbody> 
  27.     </table> 
  28.   </div> 
  29. </template> 
  30.  
  31. <script> 
  32. import axios from "axios"
  33.  
  34. export default { 
  35.   data() { 
  36.     return { 
  37.       userList: [], 
  38.     }; 
  39.   }, 
  40.   methods: { 
  41.     fetchUserList() { 
  42.       axios.get("/api/private/users").then((response) => { 
  43.         this.userList = response.data; 
  44.       }); 
  45.     }, 
  46.     deleteUser(id) { 
  47.       if (confirm("确定删除该用户吗?")) { 
  48.         axios.delete(`/api/private/users/${id}`).then(() => { 
  49.           this.fetchUserList(); 
  50.         }); 
  51.       } 
  52.     }, 
  53.   }, 
  54.   mounted() { 
  55.     this.fetchUserList(); 
  56.   }, 
  57. }; 
  58. </script> 

这个文件中,我们使用了vue-router和axios库。在fetchUserList方法中,我们使用axios库发起了一个GET请求来获取用户列表。在deleteUser方法中,我们使用axios库发起了一个DELETE请求来删除用户。

接下来我们将完成系统的权限控制部分。在Spring Security中,权限控制通常通过定义安全配置类来实现。

首先,我们需要创建一个实现了WebSecurityConfigurer接口的安全配置类SecurityConfig。在这个类中,我们可以配置用户认证和授权规则。

  1. @Configuration 
  2. @EnableWebSecurity 
  3. public class SecurityConfig extends WebSecurityConfigurerAdapter { 
  4.   
  5.     @Autowired 
  6.     private UserDetailsService userDetailsService; 
  7.   
  8.     @Override 
  9.     protected void configure(HttpSecurity http) throws Exception { 
  10.         http.csrf().disable() 
  11.                 .authorizeRequests() 
  12.                 .antMatchers("/api/public/**").permitAll() 
  13.                 .antMatchers("/api/private/**").authenticated() 
  14.                 .and().formLogin() 
  15.                 .loginPage("/login"
  16.                 .permitAll() 
  17.                 .defaultSuccessUrl("/"
  18.                 .and().logout().logoutUrl("/logout").logoutSuccessUrl("/login").invalidateHttpSession(true); 
  19.     } 
  20.   
  21.     @Override 
  22.     protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
  23.         auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); 
  24.     } 
  25.   
  26.     @Bean 
  27.     public PasswordEncoder passwordEncoder() { 
  28.         return new BCryptPasswordEncoder(); 
  29.     } 

在上述代码中,我们配置了以下规则:

所有以/api/public开头的请求都不需要认证即可访问。 所有以/api/private开头的请求都需要认证才能访问。 登录页面为/login,登录成功后默认跳转到根路径/。 注销路径为/logout,注销成功后跳转到登录页面。 在AuthenticationManagerBuilder中指定了用户认证服务和密码加密方式。 为了实现用户认证,我们需要创建一个实现了UserDetailsService接口的用户认证服务。UserDetailsService是一个Spring Security的核心接口,用于查询用户信息。我们可以通过重写该接口的loadUserByUsername方法来实现自定义的用户认证逻辑。

  1. @Service 
  2. public class UserDetailsServiceImpl implements UserDetailsService { 
  3.   
  4.     @Autowired 
  5.     private UserRepository userRepository; 
  6.   
  7.     @Override 
  8.     public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 
  9.         User user = userRepository.findByUsername(username); 
  10.         if (user == null) { 
  11.             throw new UsernameNotFoundException("用户不存在"); 
  12.         } 
  13.         List<SimpleGrantedAuthority> authorities = user.getRoles().stream() 
  14.                 .map(role -> new SimpleGrantedAuthority(role.getName())) 
  15.                 .collect(Collectors.toList()); 
  16.         return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), 
  17.                 authorities); 
  18.     } 

在上述代码中,我们通过注入UserRepository来查询用户信息。然后,我们将查询到的用户角色信息转换为Spring Security的授权信息,并返回一个UserDetails对象。

至此,我们已经完成了用户认证和权限控制的实现。通过这个系统,我们可以实现用户登录、注销和权限控制等基础功能。

12. 完整的AddUser.vue组件代码:

  1. <template> 
  2.   <div> 
  3.     <h2>Add User</h2> 
  4.     <form> 
  5.       <div class="form-group"
  6.         <label for="username">Username</label> 
  7.         <input type="text" class="form-control" id="username" v-model="user.username" required> 
  8.       </div> 
  9.       <div class="form-group"
  10.         <label for="email">Email</label> 
  11.         <input type="email" class="form-control" id="email" v-model="user.email" required> 
  12.       </div> 
  13.       <div class="form-group"
  14.         <label for="password">Password</label> 
  15.         <input type="password" class="form-control" id="password" v-model="user.password" required> 
  16.       </div> 
  17.       <div class="form-group"
  18.         <label for="roles">Roles</label> 
  19.         <select multiple class="form-control" id="roles" v-model="user.roles"
  20.           <option v-for="role in roles" :key="role.id" :value="role">{{ role.name }}</option> 
  21.         </select> 
  22.       </div> 
  23.       <button type="button" class="btn btn-primary" @click="addUser">Add User</button> 
  24.     </form> 
  25.   </div> 
  26. </template> 
  27.  
  28. <script> 
  29. import axios from 'axios'
  30.  
  31. export default { 
  32.   name: 'AddUser'
  33.   data() { 
  34.     return { 
  35.       user: { 
  36.         username: ''
  37.         email: ''
  38.         password: ''
  39.         roles: [] 
  40.       }, 
  41.       roles: [] 
  42.     } 
  43.   }, 
  44.   created() { 
  45.     axios.get('/api/roles'
  46.       .then(response => { 
  47.         this.roles = response.data; 
  48.       }) 
  49.       .catch(error => { 
  50.         console.log(error); 
  51.       }); 
  52.   }, 
  53.   methods: { 
  54.     addUser() { 
  55.       axios.post('/api/users'this.user) 
  56.         .then(response => { 
  57.           this.$router.push({ name: 'UserList' }); 
  58.         }) 
  59.         .catch(error => { 
  60.           console.log(error); 
  61.         }); 
  62.     } 
  63.   } 
  64. </script> 
  65.  
  66. <style scoped> 
  67. .form-group { 
  68.   margin-bottom: 1rem; 
  69. </style> 

在这个组件中,我们使用了Bootstrap的样式来美化表单。我们从后端获取了所有的角色列表,将其渲染到了下拉列表中。同时,我们绑定了一个addUser方法,在点击“Add User”按钮时将用户信息提交到后端创建一个新用户。

13. 完整的UserForm.vue组件代码:

  1. <template> 
  2.   <div> 
  3.     <form> 
  4.       <div class="form-group"
  5.         <label for="username">Username</label> 
  6.         <input type="text" class="form-control" id="username" v-model="user.username" required> 
  7.       </div> 
  8.       <div class="form-group"
  9.         <label for="email">Email</label> 
  10.         <input type="email" class="form-control" id="email" v-model="user.email" required> 
  11.       </div> 
  12.       <div class="form-group"
  13.         <label for="password">Password</label> 
  14.         <input type="password" class="form-control" id="password" v-model="user.password" required> 
  15.       </div> 
  16.       <div class="form-group"
  17.         <label for="roles">Roles</label> 
  18.         <select multiple class="form-control" id="roles" v-model="user.roles"
  19.           <option v-for="role in roles" :key="role.id" :value="role">{{ role.name }}</option> 
  20.         </select> 
  21.       </div> 
  22.       <button type="button" class="btn btn-primary" @click="submitForm">{{ submitButtonLabel }}</button> 
  23.     </form> 
  24.   </div> 
  25. </template> 
  26.  
  27. <script> 
  28. import axios from 'axios'
  29.  
  30. export default { 
  31.   name: 'UserForm'
  32.   props: { 
  33.     user: { 
  34.       type: Object, 
  35.       default: () => { 
  36.         return { 
  37.           username: ''
  38.           email: ''
  39.           password: ''
  40.           roles: [] 
  41.         }; 
  42.       } 
  43.     }, 
  44.     roles: { 
  45.       type: Array, 
  46.       default: () => { 
  47.         return []; 
  48.       } 
  49.     }, 
  50.     submitButtonLabel: { 
  51.       type: String, 
  52.       default'Submit' 
  53.     }, 
  54.     onSubmit: { 
  55.       type: Function, 
  56.       default: () => { 
  57.         console.log('Submit function not provided'); 
  58.       } 
  59.     } 
  60.   }, 
  61.   methods: { 
  62.     submitForm() { 
  63.       this.onSubmit(this.user); 
  64.     } 
  65.   } 
  66. </script> 
  67.  
  68. <style scoped> 
  69. .form-group { 
  70.   margin-bottom: 1rem; 
  71. </style> 

在这个组件中,我们使用了Bootstrap的样式来美化表单。我们从父组件中传递了一个user对象、roles数组和submitButtonLabel属性,分别用于渲染表单元素和提交按钮。同时,我们使用了props属性来声明这些属性。最后,我们绑定了一个submitForm方法,在点击提交按钮时将用户信息传递给父组件的onSubmit方法处理。

相关文章

站点信息