当前位置: 首页 > news >正文

【商城实战(7)】商城项目中用户信息管理功能的全栈开发

【商城实战】专栏重磅来袭!这是一份专为开发者与电商从业者打造的超详细指南。从项目基础搭建,运用 uniapp、Element Plus、SpringBoot 搭建商城框架,到用户、商品、订单等核心模块开发,再到性能优化、安全加固、多端适配,乃至运营推广策略,102 章内容层层递进。无论是想深入钻研技术细节,还是探寻商城运营之道,本专栏都能提供从 0 到 1 的系统讲解,助力你打造独具竞争力的电商平台,开启电商实战之旅。

目录

  • 一、移动前端用户信息展示页面开发
    • 1.1 搭建基础页面结构
    • 1.2 实现信息展示功能
    • 1.3 完成编辑切换逻辑
  • 二、PC 前端用户信息展示页面开发
    • 2.1 创建 PC 端项目架构
    • 2.2 设计展示页面布局
    • 2.3 实现编辑切换功能
  • 三、后端用户信息查询、更新接口编写
    • 3.1 配置项目环境
    • 3.2 编写查询接口
    • 3.3 编写更新接口
    • 3.4 确保数据安全与准确
  • 四、前端信息校验逻辑实现
    • 4.1 手机号格式校验
    • 4.2 邮箱格式校验
    • 4.3 减少无效请求的策略


一、移动前端用户信息展示页面开发

在商城项目中,使用 uniapp 开发移动前端用户信息展示及编辑切换页面,能够为用户提供便捷的个人信息管理体验。以下是具体的开发步骤和关键技术点。

1.1 搭建基础页面结构

首先,确保已经安装了 HBuilderX 开发工具。打开 HBuilderX,创建一个新的 uniapp 项目(如果您此前已依照专栏文章完成项目创建,该步骤可省略)。在项目创建过程中,填写项目名称、选择项目创建位置,并勾选需要支持的移动端平台,如微信小程序、支付宝小程序、APP 等。这里我们选择默认的 Hello Uni-app 模板,该模板为我们提供了一个基础的项目结构,方便后续开发。

在项目的pages目录下,创建一个新的页面,命名为userInfo。在userInfo目录下,创建userInfo.vue文件,这将是我们用户信息展示页面的核心文件。在userInfo.vue中,使用template标签搭建页面的基本布局。例如,我们可以使用view组件作为容器,将页面划分为头部、内容和底部三个部分。头部用于显示页面标题,内容部分展示用户的各项信息,底部可以放置操作按钮,如保存、取消等。

同时,引入自定义的样式文件,对页面进行样式设置。通过style标签,使用 CSS 或 SCSS 语法,设置页面的背景颜色、字体样式、间距等。例如,设置页面背景为浅灰色,字体颜色为黑色,标题字体加粗等,使页面看起来更加美观和舒适。

1.2 实现信息展示功能

从后端获取用户信息是实现信息展示的关键步骤。在userInfo.vue的script标签中,使用uni.request方法向服务器发送 HTTP 请求,获取用户信息。例如:

export default {
  data() {
    return {
      user: {}
    };
  },
  mounted() {
    this.fetchUserInfo();
  },
  methods: {
    fetchUserInfo() {
      uni.request({
        url: 'https://your-backend-api.com/user/info', // 后端接口地址
        method: 'GET',
        success: (res) => {
          if (res.statusCode === 200) {
            this.user = res.data;
          }
        },
        fail: (err) => {
          console.log('获取用户信息失败', err);
        }
      });
    }
  }
};

获取到用户信息后,通过数据绑定将其展示在页面上。在template标签中,使用 Mustache 语法({{}})将user对象中的属性值绑定到对应的 HTML 元素上。例如:

<template>
  <view class="container">
    <view class="header">{{user.username}}的个人信息</view>
    <view class="content">
      <view class="item">
        <text class="label">姓名:</text>
        <text class="value">{{user.name}}</text>
      </view>
      <view class="item">
        <text class="label">手机号:</text>
        <text class="value">{{user.phone}}</text>
      </view>
      <view class="item">
        <text class="label">邮箱:</text>
        <text class="value">{{user.email}}</text>
      </view>
    </view>
  </view>
</template>

这样,当页面加载时,就会从后端获取用户信息并展示在相应的位置。

1.3 完成编辑切换逻辑

为了实现用户信息编辑切换的交互效果,我们需要添加编辑按钮,并在点击按钮时切换页面状态。在template标签中,添加一个编辑按钮:

<view class="footer">
  <button @click="toggleEdit">{{editMode ? '保存' : '编辑'}}</button>
</view>

在script标签中,定义editMode变量来表示当前页面的编辑状态,并实现toggleEdit方法来切换编辑状态:

export default {
  data() {
    return {
      user: {},
      editMode: false
    };
  },
  // 省略其他代码
  methods: {
    toggleEdit() {
      this.editMode =!this.editMode;
      if (!this.editMode) {
        // 保存编辑后的信息,调用后端更新接口
        this.saveUserInfo();
      }
    },
    saveUserInfo() {
      uni.request({
        url: 'https://your-backend-api.com/user/update', // 后端更新接口地址
        method: 'POST',
        data: this.user,
        success: (res) => {
          if (res.statusCode === 200) {
            uni.showToast({
              title: '保存成功',
              icon:'success'
            });
          }
        },
        fail: (err) => {
          console.log('保存用户信息失败', err);
          uni.showToast({
            title: '保存失败',
            icon: 'none'
          });
        }
      });
    }
  }
};

当点击编辑按钮时,toggleEdit方法会将editMode取反。如果editMode为true,表示进入编辑状态,此时可以将展示信息的text组件替换为input组件,方便用户进行编辑。例如:

<view class="content">
  <view class="item">
    <text class="label">姓名:</text>
    <view v-if="editMode">
      <input v-model="user.name" />
    </view>
    <text v-else class="value">{{user.name}}</text>
  </view>
  <!-- 其他信息类似处理 -->
</view>

通过以上步骤,我们就完成了移动前端用户信息展示页面的开发,支持信息编辑切换功能,为用户提供了良好的交互体验。

二、PC 前端用户信息展示页面开发

在 PC 端,我们运用 Element Plus 来开发用户信息展示及编辑切换页面,Element Plus 基于 Vue 3,提供了丰富的组件和现代化的 API,能帮助我们高效构建美观且交互性强的界面。

2.1 创建 PC 端项目架构

注意:如果您此前已依照专栏文章完成项目创建,该步骤可省略。

首先,确保本地已安装 Node.js 环境。打开命令行工具,使用 Vue CLI 创建一个新的 Vue 项目:

vue create pc-userinfo-project

在创建过程中,根据提示选择 Vue 3,并按需选择其他配置,如是否使用 TypeScript、ESLint 等。这里我们选择默认配置,快速搭建项目基础。
项目创建完成后,进入项目目录:

cd pc-userinfo-project

接着,安装 Element Plus 组件库,在命令行中执行:

npm install element-plus --save

安装完成后,在main.js中引入 Element Plus 及其样式:

import { createApp } from 'vue'
import App from './App.vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'

const app = createApp(App)
app.use(ElementPlus)
app.mount('#app')

这样,我们就完成了 PC 端项目架构的搭建,为后续页面开发做好了准备。

2.2 设计展示页面布局

在src/views目录下创建UserInfo.vue文件,这将是我们的用户信息展示页面。使用 Element Plus 的布局组件,如el-container、el-aside、el-main等,来设计页面布局。例如:

<template>
  <el-container class="user-info-container">
    <el-aside width="200px">
      <!-- 侧边栏,可以放置导航等内容 -->
    </el-aside>
    <el-main>
      <div class="user-info-content">
        <h2>用户信息</h2>
        <el-form :model="user" label-width="120px">
          <el-form-item label="用户名">
            <span>{{user.username}}</span>
          </el-form-item>
          <el-form-item label="姓名">
            <span>{{user.name}}</span>
          </el-form-item>
          <el-form-item label="手机号">
            <span>{{user.phone}}</span>
          </el-form-item>
          <el-form-item label="邮箱">
            <span>{{user.email}}</span>
          </el-form-item>
        </el-form>
      </div>
    </el-main>
  </el-container>
</template>

<script>
export default {
  data() {
    return {
      user: {}
    };
  },
  mounted() {
    // 模拟从后端获取用户信息
    this.user = {
      username: 'testuser',
      name: '张三',
      phone: '13800138000',
      email: 'zhangsan@example.com'
    };
  }
};
</script>

<style scoped>
.user-info-container {
  height: 100vh;
}
.user-info-content {
  padding: 20px;
}
</style>

通过上述代码,我们创建了一个包含侧边栏和主要内容区域的页面布局。主要内容区域展示了用户的各项信息,使用el-form和el-form-item组件进行布局,使页面看起来整齐、美观。同时,通过scoped样式,为当前组件设置了私有样式,避免影响其他组件。

2.3 实现编辑切换功能

为了实现编辑切换功能,我们需要添加编辑按钮,并在点击按钮时切换页面状态。在UserInfo.vue的template中添加编辑按钮:

<el-button type="primary" @click="toggleEdit">{{editMode ? '保存' : '编辑'}}</el-button>

在script中定义editMode变量来表示当前页面的编辑状态,并实现toggleEdit方法来切换编辑状态:

export default {
  data() {
    return {
      user: {},
      editMode: false
    };
  },
  mounted() {
    // 模拟从后端获取用户信息
    this.user = {
      username: 'testuser',
      name: '张三',
      phone: '13800138000',
      email: 'zhangsan@example.com'
    };
  },
  methods: {
    toggleEdit() {
      this.editMode =!this.editMode;
      if (!this.editMode) {
        // 保存编辑后的信息,调用后端更新接口
        this.saveUserInfo();
      }
    },
    saveUserInfo() {
      // 这里模拟调用后端更新接口
      console.log('保存用户信息', this.user);
    }
  }
};

当进入编辑状态时,将展示信息的span组件替换为el-input组件,方便用户进行编辑。例如:

<el-form-item label="姓名">
  <el-input v-if="editMode" v-model="user.name"></el-input>
  <span v-else>{{user.name}}</span>
</el-form-item>

通过以上步骤,我们在 PC 端实现了用户信息展示页面的编辑切换功能,用户可以方便地查看和修改自己的个人信息。

三、后端用户信息查询、更新接口编写

在商城系统中,后端的用户信息查询与更新接口是保证用户数据管理的关键部分。使用 Spring Boot 可以高效地开发这些接口,以下将详细介绍其实现过程。

3.1 配置项目环境

注意:如果您此前已依照专栏文章完成项目创建,该步骤可省略。

首先,使用 Spring Initializr 创建一个新的 Spring Boot 项目。可以通过访问Spring Initializr 官网,在网页上进行项目初始化配置。在配置页面中,填写项目的基本信息,如 Group(组 ID,一般为公司域名反写,例如com.example)、Artifact(项目 ID,如mall-user-service)、Name(项目名称,可自定义)、Description(项目描述,简要说明项目用途)、Package Name(包名,建议与 Group 一致)等。

在依赖选择部分,添加Spring Web依赖,用于创建 RESTful 风格的 Web 接口;添加MySQL Driver依赖,以连接 MySQL 数据库;添加MyBatis Framework依赖,方便进行数据库操作。例如,在pom.xml文件中,添加的依赖如下:

<dependencies>
    <!-- Spring Web依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- MySQL驱动依赖 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <!-- MyBatis依赖 -->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.2.2</version>
    </dependency>
</dependencies>

配置完成后,点击 “Generate” 按钮,下载生成的项目压缩包。解压后,使用 IDE(如 IntelliJ IDEA 或 Eclipse)打开项目。

接着,在src/main/resources目录下,找到application.properties文件(如果是 Spring Boot 2.x 版本,也可使用application.yml文件),配置数据库连接信息。假设 MySQL 数据库的地址为localhost,端口为3306,数据库名为mall,用户名和密码分别为root和123456,则配置如下:

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mall?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456

或者使用application.yml配置:

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mall?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
    username: root
    password: 123456

这样,就完成了项目环境的配置,为后续编写接口做好了准备。

3.2 编写查询接口

在src/main/java目录下,按照 MVC(Model - View - Controller)架构创建相应的包和类。首先,创建entity包,用于存放实体类。例如,创建User实体类,用于表示用户信息:

package com.example.mall.entity;

import lombok.Data;

@Data
public class User {
    private Long id;
    private String username;
    private String password;
    private String phone;
    private String email;
    // 其他用户信息字段
}

使用lombok的@Data注解,自动生成getter、setter、equals、hashCode和toString方法,简化代码编写。

接着,创建mapper包,用于存放数据库操作接口。在mapper包下,创建UserMapper接口,用于定义用户信息查询方法:

package com.example.mall.mapper;

import com.example.mall.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface UserMapper {
    @Select("SELECT * FROM user WHERE id = #{id}")
    User findUserById(Long id);
}

使用@Mapper注解,将该接口标记为 MyBatis 的 Mapper,Spring Boot 会自动扫描并将其注册到容器中。@Select注解用于编写 SQL 查询语句,这里通过用户 ID 查询用户信息。

然后,创建service包,用于存放业务逻辑层代码。在service包下,创建UserService接口及其实现类UserServiceImpl。UserService接口定义了查询用户信息的方法:

package com.example.mall.service;

import com.example.mall.entity.User;

public interface UserService {
    User findUserById(Long id);
}

UserServiceImpl实现类实现了UserService接口,并调用UserMapper进行数据库查询操作:

package com.example.mall.service.impl;

import com.example.mall.entity.User;
import com.example.mall.mapper.UserMapper;
import com.example.mall.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User findUserById(Long id) {
        return userMapper.findUserById(id);
    }
}

在UserServiceImpl中,使用@Autowired注解自动注入UserMapper,实现依赖注入。

最后,创建controller包,用于存放控制器层代码。在controller包下,创建UserController类,用于处理前端的请求,并返回查询结果:

package com.example.mall.controller;

import com.example.mall.entity.User;
import com.example.mall.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    public User findUserById(@PathVariable Long id) {
        return userService.findUserById(id);
    }
}

@RestController注解表示该类是一个 RESTful 风格的控制器,返回的数据会以 JSON 格式返回给前端。@RequestMapping注解用于指定请求路径,这里将所有以/user开头的请求映射到该控制器。@GetMapping注解用于处理 HTTP GET 请求,@PathVariable注解用于获取路径中的参数,这里获取用户 ID,调用UserService的findUserById方法查询用户信息并返回。

3.3 编写更新接口

在UserMapper接口中,添加更新用户信息的方法:

package com.example.mall.mapper;

import com.example.mall.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

@Mapper
public interface UserMapper {
    @Select("SELECT * FROM user WHERE id = #{id}")
    User findUserById(Long id);

    @Update("UPDATE user SET username = #{username}, phone = #{phone}, email = #{email} WHERE id = #{id}")
    int updateUser(User user);
}

@Update注解用于编写 SQL 更新语句,这里根据用户 ID 更新用户的用户名、手机号和邮箱。

在UserService接口中,添加更新用户信息的方法:

package com.example.mall.service;

import com.example.mall.entity.User;

public interface UserService {
    User findUserById(Long id);
    boolean updateUser(User user);
}

在UserServiceImpl实现类中,实现更新用户信息的方法:

package com.example.mall.service.impl;

import com.example.mall.entity.User;
import com.example.mall.mapper.UserMapper;
import com.example.mall.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User findUserById(Long id) {
        return userMapper.findUserById(id);
    }

    @Override
    public boolean updateUser(User user) {
        int result = userMapper.updateUser(user);
        return result > 0;
    }
}

在UserController中,添加处理更新用户信息请求的方法:

package com.example.mall.controller;

import com.example.mall.entity.User;
import com.example.mall.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    public User findUserById(@PathVariable Long id) {
        return userService.findUserById(id);
    }

    @PutMapping
    public ResponseEntity<String> updateUser(@RequestBody User user) {
        boolean success = userService.updateUser(user);
        if (success) {
            return new ResponseEntity<>("用户信息更新成功", HttpStatus.OK);
        } else {
            return new ResponseEntity<>("用户信息更新失败", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}

@PutMapping注解用于处理 HTTP PUT 请求,@RequestBody注解用于接收前端传递的 JSON 格式的用户数据,将其转换为User对象。调用UserService的updateUser方法更新用户信息,并根据更新结果返回相应的响应给前端。

3.4 确保数据安全与准确

在编写后端接口时,采取以下措施确保数据的安全与准确:

  1. 数据校验:在控制器层,对前端传递过来的数据进行校验。例如,使用Hibernate Validator对User实体类中的字段进行校验。在User实体类中,添加校验注解:
package com.example.mall.entity;

import lombok.Data;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;

@Data
public class User {
    private Long id;
    @NotBlank(message = "用户名不能为空")
    private String username;
    // 其他字段校验注解
    @Email(message = "邮箱格式不正确")
    private String email;
}

在UserController的更新接口方法中,添加@Validated注解开启校验:

@PutMapping
public ResponseEntity<String> updateUser(@RequestBody @Validated User user) {
    // 处理更新逻辑
}

这样,当前端传递的数据不符合校验规则时,会返回错误信息给前端,避免非法数据进入数据库。

  1. 事务处理:对于涉及数据库更新操作的方法,使用事务进行管理。在UserServiceImpl的updateUser方法上添加@Transactional注解:
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public boolean updateUser(User user) {
        int result = userMapper.updateUser(user);
        return result > 0;
    }
}

当updateUser方法中的数据库操作出现异常时,事务会自动回滚,保证数据的一致性和完整性。

  1. 权限控制:在实际应用中,根据用户角色和权限,控制对用户信息查询和更新接口的访问。可以使用 Spring Security 框架进行权限管理。首先,添加 Spring Security 依赖到pom.xml文件中:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

然后,在src/main/java目录下创建security包,在该包下创建SecurityConfig类,配置权限规则:

package com.example.mall.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
           .authorizeRequests()
               .antMatchers("/user/{id}").hasRole("USER")
               .antMatchers("/user").hasRole("ADMIN")
               .anyRequest().authenticated()
               .and()
           .formLogin()
               .and()
           .httpBasic();
    }

    @Bean
    @Override
    public InMemoryUserDetailsManager userDetailsService() {
        UserDetails user = User.withDefaultPasswordEncoder()
               .username("user")
               .password("password")
               .roles("USER")
               .build();
        UserDetails admin = User.withDefaultPasswordEncoder()
               .username("admin")
               .password("admin")
               .roles("ADMIN")
               .build();
        return new InMemoryUserDetailsManager(user, admin);
    }
}

上述配置中,只有具有USER角色的用户可以访问/user/{id}接口,具有ADMIN角色的用户可以访问/user接口,其他请求需要认证后才能访问。通过这些措施,可以有效确保后端接口的数据安全与准确,为商城系统的稳定运行提供保障。

四、前端信息校验逻辑实现

在用户信息管理功能中,前端信息校验逻辑起着至关重要的作用。它能够确保用户输入的数据符合格式要求,减少无效请求,提升用户体验,同时减轻后端服务器的负载。以下将详细介绍手机号、邮箱格式校验的实现方法以及减少无效请求的策略。

4.1 手机号格式校验

在前端,通常使用正则表达式来实现手机号格式校验。以 uniapp 开发的移动前端为例,假设在用户信息编辑页面有一个输入手机号的input组件,绑定的数据为user.phone,校验代码如下:

<template>
  <view class="item">
    <text class="label">手机号:</text>
    <input v-model="user.phone" @blur="validatePhone" />
    <text v-if="phoneError" class="error">{{phoneError}}</text>
  </view>
</template>

<script>
export default {
  data() {
    return {
      user: {},
      phoneError: ''
    };
  },
  methods: {
    validatePhone() {
      const reg = /^1[3456789]\d{9}$/;
      if (!reg.test(this.user.phone)) {
        this.phoneError = '手机号格式不正确';
      } else {
        this.phoneError = '';
      }
    }
  }
};
</script>

上述代码中,@blur事件表示当输入框失去焦点时触发validatePhone方法。在validatePhone方法中,定义了一个正则表达式/^1[3456789]\d{9}$/,它的含义是:

  • ^:表示匹配字符串的开头。
  • 1:必须以数字 1 开头。
  • [3456789]:第二位必须是 3、4、5、6、7、8 或 9 中的一个。
  • \d{9}:后面必须跟着 9 个数字。
  • $:表示匹配字符串的结尾。

通过reg.test(this.user.phone)方法来测试用户输入的手机号是否符合该正则表达式的格式要求。如果不符合,设置phoneError提示错误信息;如果符合,则清空phoneError。

4.2 邮箱格式校验

同样,对于邮箱格式校验也可以使用正则表达式。在 PC 端使用 Element Plus 开发的用户信息编辑页面中,假设el-form表单中有一个邮箱输入项,代码如下:

<template>
  <el-form :model="user" label-width="120px">
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="user.email" @blur="validateEmail"></el-input>
      <el-form-item :error="emailError" v-if="emailError"></el-form-item>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  data() {
    return {
      user: {},
      emailError: ''
    };
  },
  methods: {
    validateEmail() {
      const reg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
      if (!reg.test(this.user.email)) {
        this.emailError = '邮箱格式不正确';
      } else {
        this.emailError = '';
      }
    }
  }
};
</script>

这里的正则表达式/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/含义为:

  • ^:匹配字符串的开头。
  • [a-zA-Z0-9._%+-]+:表示邮箱前缀,可以包含字母、数字、下划线、点号、百分号、加号、减号,且至少出现一次。
  • @:必须包含一个 @符号。
  • [a-zA-Z0-9.-]+:表示邮箱域名部分,可以包含字母、数字、点号、减号,且至少出现一次。
  • \.:匹配一个点号。
  • [a-zA-Z]{2,}:表示顶级域名,由 2 个或更多的字母组成。

当用户输入邮箱并失去焦点时,触发validateEmail方法,通过正则表达式测试邮箱格式是否正确,并根据结果显示相应的错误提示。

4.3 减少无效请求的策略

通过前端信息校验逻辑,可以有效减少无效请求,具体策略如下:

  1. 实时校验:在用户输入数据的过程中实时进行校验,如上述手机号和邮箱校验,当用户输入完成并失去焦点时立即检查格式。这样可以让用户及时了解自己输入的错误,避免在提交表单时才发现问题,提高用户体验。
  2. 阻止提交:在表单提交事件中,先检查所有需要校验的字段是否通过校验。如果存在未通过校验的字段,阻止表单提交,并提示用户相应的错误信息。例如,在 uniapp 中:
<template>
  <form @submit.prevent="submitForm">
    <!-- 表单内容 -->
    <button form-type="submit">提交</button>
  </form>
</template>

<script>
export default {
  methods: {
    submitForm() {
      this.validatePhone();
      this.validateEmail();
      if (this.phoneError || this.emailError) {
        return;
      }
      // 提交表单逻辑
    }
  }
};
</script>

在上述代码中,@submit.prevent阻止表单的默认提交行为,在submitForm方法中先进行手机号和邮箱的校验,如果存在错误,则直接返回,不执行提交表单的逻辑,从而避免向后端发送无效请求。

  1. 优化用户交互:在错误提示方面,采用友好、明确的提示信息,告知用户具体的错误原因和正确的格式要求。同时,可以使用不同的颜色或样式突出显示错误字段,让用户更容易注意到。例如,在 Element Plus 中,可以通过设置el-form-item的error属性来显示错误信息,并通过 CSS 样式设置错误信息的颜色和样式。这样,通过完善的前端信息校验逻辑和合理的减少无效请求策略,能够提高商城系统用户信息管理功能的稳定性和可靠性,为用户提供更好的使用体验。

相关文章:

  • java使用第三方库 semver4j 处理语义化版本,递增,对比等操作
  • 初识Python:一门简洁而强大的编程语言
  • 大语言模型(LLM)和嵌入模型的统一调用接口
  • GB28181开发--SRS+Jessibuca‌
  • LINUX网络基础 [一] - 初识网络,理解网络协议
  • 集合论--形式化语言里的汇编码
  • vulnhub渗透日记23:bulldog
  • SQLite Having 子句详解
  • java基础100道面试题
  • AT32F421专题---PA9 PA10的I2C1连接AT24C02失败及解决
  • Diffusion模型中时间t嵌入的方法
  • Teaching Small Language Models Reasoning throughCounterfactual Distillation
  • Hive-07之企业级调优
  • Docker部署MySQL
  • Python:简单的爬虫程序,从web页面爬取图片与标题并保存MySQL
  • 大模型核心要素完全解析:从数字神经元到智能对话的奥秘
  • go语言数据类型
  • (50)[HGAME 2023 week2]before_main
  • AutoGen学习笔记系列(六)Tutorial - Termination
  • unittest框架 核心知识的系统复习及与pytest的对比
  • 思想史家陈谷嘉逝世,曾为岳麓书院当代复兴奠定重要基础
  • 以军向也门3个港口的居民发布撤离令
  • 微软将裁员3%,减少管理层
  • 乌拉圭前总统何塞·穆希卡去世
  • 首映|奥斯卡最佳国际影片《我仍在此》即将公映
  • 沈阳卫健委通报“健康证”办理乱象:涉事医院已被立案查处