综合演习开发--简阅--用户登录功能

1.创建数据库db_jianyue,并创建数据库表t_user


t_user.png
  • 插入数据


    t_user.data.png

2.后端:新建一个新的模块jianyue-api


jianyue-api.png

config配置
controller控制器
entity
dto只有账号密码,数据传输对象
util工具类
service业务逻辑impl具体实现类

2.1 pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.soft1721</groupId>
    <artifactId>jianyue-api</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>jianyue-api</name>
    <description>JianYue API project</description>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
<!--序列的解析工具-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.56</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.39</version>
        </dependency>

<!--增加阿里云短信服务SDK依赖和SpringBoot集成redis依赖-->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.0.3</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>2.8.3</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.6</version>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>com.spring4all</groupId>
            <artifactId>swagger-spring-boot-starter</artifactId>
            <version>1.8.0.RELEASE</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

application.properties文件

## 数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/db_jianyue?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#指定实体类映射的包
mybatis.type-aliases-package=com.soft1721.jianyue.api.entity

#swagger配置
swagger.enabled=true
swagger.title=jianyue  api project
swagger.description=Starter for swagger 2.x
swagger.license=Apache License, Version 2.0
swagger.licenseUrl=https://www.apache.org/licenses/LICENSE-2.0.html
swagger.termsOfServiceUrl=https://github.com/dyc87112/spring-boot-starter-swagger
swagger.contact.name=zhangli
swagger.contact.url=//www.greatytc.com/u/f2a0d66f112f
swagger.contact.email=1459816730@qq.com
swagger.base-package=com.soft1721.jianyue.api.controller
swagger.base-path=/**
swagger.exclude-path=/error, /ops/**

entity中的User.java类

package com.soft1721.jianyue.api.entity;

import lombok.Data;

import java.util.Date;

@Data

public class User {
    private Integer id;
    private String mobile;
    private String password;
    private String nickname;
    private String token;
    private Short status;
    private Date regtime;
    private String avatar;


}

entity子包中的dto包下的UserDTO.java数据传输对象

package com.soft1721.jianyue.api.entity.dto;

import lombok.Data;

@Data
public class UserDTO {
    private String mobile;
    private String password;
}

util包下有四个类


mmexport1555477018753.png
  • MsgConst类
package com.soft1721.jianyue.api.util;

public class MsgConst {
    public static final String SUCCESS = "请求成功";
    public static final String USER_ID_NO_FOUND = "id不存在";
    public static final String USER_MOBILE_NO_FOUND = "手机号不存在";
    public static final String PASSWORD_ERROR = "密码错误";
    public static final String USER_STATUS_ERROR = "账号异常";
    public static final String MOBILE_EXIST = "手机号已被注册";
    public static final String VERIFYCODE_ERROR = "验证码错误";
    
}
  • ResponseResult类
package com.soft1721.jianyue.api.util;

import lombok.Data;
import lombok.Setter;

/**
 * 封装统一的响应体
 * 调用 ResponseResult.success() 或 ResponseResult.success(Object data),
 * 不需要返回数据时调用前者, 需要返回数据时调用后者
 */
@Data
public class ResponseResult {
    private int code;
    private String msg;
    private Object data;

    public static ResponseResult error(int code, String msg) {
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(code);
        responseResult.setMsg(msg);
        return responseResult;
    }

    public static ResponseResult success() {
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(StatusConst.SUCCESS);
        responseResult.setMsg(MsgConst.SUCCESS);
        return responseResult;
    }

    public static ResponseResult success(Object data) {
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(StatusConst.SUCCESS);
        responseResult.setMsg(MsgConst.SUCCESS);
        responseResult.setData(data);
        return responseResult;
    }
}
  • StatusConst类
package com.soft1721.jianyue.api.util;

public class StatusConst {
    public static final int SUCCESS = 0;
    public static final int USER_ID_NOT_FOUND = 1;
    public static final int USER_MOBILE_NOT_FOUND = 2;
    public static final int PASSWORD_ERROR = 3;
    public static final int USER_STATUS_ERROR = 4;
    public static final int MOBILE_EXIST = 5;
    public static final int VERIFYCODE_ERROR = 6;
}
  • StringUtil类
package com.soft1721.jianyue.api.util;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
public class StringUtil {
    public static String getDateString(Date date) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return df.format(date);
    }
    public static String getBase64Encoder(String srcString) {
        String resultStr = "";
        try {
            resultStr = Base64.getEncoder().encodeToString(srcString.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return resultStr;
    }
    public static String getBase64Decoder(String srcString) {
        byte[] bytes = Base64.getDecoder().decode(srcString);
        return new String(bytes);
    }
    public static String getUUIDString() {
        return UUID.randomUUID().toString();
    }
    public static String getVerifyCode() {
        Random random = new Random();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            stringBuilder.append(String.valueOf(random.nextInt(10)));
        }
        return stringBuilder.toString();
    }
}
  • mapper包下的UserMapper.java接口
package com.soft1721.jianyue.api.mapper;

import com.soft1721.jianyue.api.entity.User;
import org.apache.ibatis.annotations.*;

public interface UserMapper {
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "mobile", column = "mobile"),
            @Result(property = "password", column = "password"),
            @Result(property = "nickname", column = "nickname"),
            @Result(property = "avatar", column = "avatar"),
            @Result(property = "status", column = "status"),
            @Result(property = "regtime", column = "regtime"),
            @Result(property = "token", column = "token")
    })
    @Select("SELECT * FROM t_user WHERE mobile = #{mobile} ")
    User getUserByMobile(String mobile);

    @Update("UPDATE t_user SET password=#{password},nickname=#{nickname},avatar=#{avatar},status=#{status},token=#{token} WHERE id =#{id}")
    void update(User user);

    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "mobile", column = "mobile"),
            @Result(property = "password", column = "password"),
            @Result(property = "nickname", column = "nickname"),
            @Result(property = "avatar", column = "avatar"),
            @Result(property = "status", column = "status"),
            @Result(property = "regtime", column = "regtime"),
            @Result(property = "token", column = "token")
    })
    @Select("SELECT * FROM  t_user WHERE id = #{id}")
    User getUserById(int userId);
    @Update("UPDATE t_user SET nickname=#{nickname} WHERE id =#{id}")
    void nickname(User user);


    @Insert("INSERT INTO t_user(mobile,password,nickname,status,regtime,avatar) VALUES(#{mobile},#{password},#{nickname},#{status},#{regtime},#{avatar}) ")
    void insert(User user1);
}
  • service包下的UserService.java接口
package com.soft1721.jianyue.api.service;

import com.soft1721.jianyue.api.entity.User;
import com.soft1721.jianyue.api.entity.dto.UserDTO;

public interface UserService {

    /**
     * 根据手机号获取用户信息
     *
     * @param mobile
     * @return
     */
    User getUserByMobile(String mobile);

    /**
     * 登录方法
     *
     * @param userDTO
     * @return boolean
     */
    int signIn(UserDTO userDTO);

    User getUserById(int userId);

    void updateUser(User user);

    int signUp(UserDTO userDTO);

    void nickname(User user);
}
  • UserServiceImpl实现类
package com.soft1721.jianyue.api.service.impl;

import com.soft1721.jianyue.api.entity.User;
import com.soft1721.jianyue.api.entity.dto.UserDTO;
import com.soft1721.jianyue.api.mapper.UserMapper;
import com.soft1721.jianyue.api.service.UserService;
import com.soft1721.jianyue.api.util.StatusConst;
import com.soft1721.jianyue.api.util.StringUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

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

    @Override
    public User getUserByMobile(String mobile) {

        return userMapper.getUserByMobile(mobile);
    }

    @Override
    public int signIn(UserDTO userDTO) {
        User user = userMapper.getUserByMobile(userDTO.getMobile());
        //手机号存在
        if (user != null) {
            //密码正确
            if (userDTO.getPassword().equals(user.getPassword())) {
                //账号正常
                if (user.getStatus() == 1) {
                    user.setToken(StringUtil.getUUIDString());
                    userMapper.update(user);
                    return StatusConst.SUCCESS;
                } else {  //账号异常
                    return StatusConst.USER_STATUS_ERROR;
                }
            } else {  //密码错误
                return StatusConst.PASSWORD_ERROR;
            }
        } else {  //手机号不存在
            return StatusConst.USER_MOBILE_NOT_FOUND;
        }
    }

    @Override
    public User getUserById(int userId) {
        return userMapper.getUserById(userId);
    }

    @Override
    public void updateUser(User user) {
        userMapper.update(user);

    }

    @Override
    public int signUp(UserDTO userDTO) {
        //先根据手机号找用户是否存在
        User user = userMapper.getUserByMobile(userDTO.getMobile());
        if (user != null) {
            return StatusConst.MOBILE_EXIST;
        } else {
            User user1 = new User();
            user1.setMobile(userDTO.getMobile());
            user1.setPassword(StringUtil.getBase64Encoder(userDTO.getPassword()));
            user1.setNickname("新用户");
            user1.setAvatar("http://niit-soft.oss-cn-hangzhou.aliyuncs.com/avatar/default.png?Expires=1554292133&OSSAccessKeyId=TMP.AQHz8QArrtzxbb3VQMkjjdlwB2JvoOvmIMBh4CoHPerk718LdNehNeLBWDEcMC4CFQDgleDgj6q_VsjSB-9lTP7KcdjU1gIVAOnRS2ovGQSHNf9WpHc4nSLw0-OH&Signature=NT9%2BSOt7FX4VvmQnvt7B8XvKtmA%3D");
            user1.setRegtime(new Date());
            user1.setStatus((short) 1);
            userMapper.insert(user1);
            return StatusConst.SUCCESS;
        }
    }

    @Override
    public void nickname(User user) {
        userMapper.nickname(user);
    }
    }

  • 单元测试
package com.soft1721.jianyue.api.service.impl;

import com.soft1721.jianyue.api.entity.User;
import com.soft1721.jianyue.api.entity.dto.UserDTO;
import com.soft1721.jianyue.api.service.UserService;
import com.soft1721.jianyue.api.util.StatusConst;
import com.soft1721.jianyue.api.util.StringUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;

import static org.junit.Assert.assertEquals;


/**
 *
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceImplTest {
    @Resource
    private UserService userService;

    @Test
    public void getUserByMobile() {
        User user = userService.getUserByMobile("13988889999");
        System.out.println(user);
    }

    @Test
    public void signIn() {
        UserDTO loginUser = new UserDTO();
        loginUser.setMobile("13951905171");
        String base64Pass = StringUtil.getBase64Encoder("111");
        loginUser.setPassword(base64Pass);
        int status = userService.signIn(loginUser);
        assertEquals(StatusConst.SUCCESS, status);
    }
    @Test
    public void signUp() {
        UserDTO userDTO = new UserDTO();
        userDTO.setMobile("18315158147");
        userDTO.setPassword("111");
        int n = userService.signUp(userDTO);
        assertEquals(0, n);
    }


    @Test
    public void nickname() {
        User user=userService.getUserById(1);
        user.setNickname("明天");
        userService.updateUser(user);

    }
}
  • UserController类
package com.soft1721.jianyue.api.controller;


import com.soft1721.jianyue.api.entity.User;

import com.soft1721.jianyue.api.entity.dto.UserDTO;

import com.soft1721.jianyue.api.service.UserService;

import com.soft1721.jianyue.api.util.ResponseResult;

import com.soft1721.jianyue.api.util.MsgConst;

import com.soft1721.jianyue.api.util.StatusConst;

import com.soft1721.jianyue.api.util.StringUtil;

import org.springframework.web.bind.annotation.*;


import javax.annotation.Resource;


@RestController

@RequestMapping(value = "/api/user")

public class UserController {

@Resource

private UserService userService;


@PostMapping(value = "/sign_in")

public ResponseResult signIn(@RequestBody UserDTO userDTO) {

 System.out.println(userDTO);

User user = userService.getUserByMobile(userDTO.getMobile());

if (user == null) {

return ResponseResult.error(StatusConst.USER_MOBILE_NOT_FOUND, MsgConst.USER_MOBILE_NO_FOUND);

} else {

//手机号存在,将明文密码转成Base64密文后进行登录

userDTO.setPassword(StringUtil.getBase64Encoder(userDTO.getPassword()));

int status = userService.signIn(userDTO);

if (status == StatusConst.SUCCESS) {

return ResponseResult.success(user);

} else if (status == StatusConst.PASSWORD_ERROR) {

return ResponseResult.error(status, MsgConst.PASSWORD_ERROR);

} else {

return ResponseResult.error(status, MsgConst.USER_STATUS_ERROR);
        }
     }
  }
}
  • config包下跨域配置类
package com.soft1721.jianyue.api.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
class WebMvcConfigurer extends WebMvcConfigurerAdapter {
    //跨域配置
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            //重写父类提供的跨域请求处理的接口
            public void addCorsMappings(CorsRegistry registry) {
                //添加映射路径
                registry.addMapping("/**")
                        //放行哪些原始域
                        .allowedOrigins("*")
                        //是否发送Cookie信息
                        .allowCredentials(true)
                        //放行哪些原始域(请求方式)
                        .allowedMethods("GET", "POST", "PUT", "DELETE")
                        //放行哪些原始域(头部信息)
                        .allowedHeaders("*")
                        //暴露哪些头部信息(因为跨域访问默认不能获取全部头部信息)
                        .exposedHeaders("Header1", "Header2");
            }
        };
    }
}

启动主类:需要在主类里面加入注解
@SpringBootApplication
@MapperScan("com.soft1721.jianyue.api.mapper")

打开浏览器输入localhost:8080/swagger-ui.html远程接口测试接口
如果出现200,说明后端已经通了

前端:在HBuilderX创建uni-app类型的项目


jianyue.png
  • commons目录放置全局配置函数

  • components放置封装的组件

  • pages放置页面文件

  • static目录放置图片资源

  • style放置全局样式文件

  • 配置pages.json文件:

{
    "pages": [
        //pages数组中第一项表示应用启动页,参考:https://uniapp.dcloud.io/collocation/pages
        {
            "path": "pages/index/index",
            "style": {
                "navigationBarTitleText": "文章",
                //允许下拉刷新
                "enablePullDownRefresh": true
            }
        },
        {
            "path": "pages/message/message",
            "style": {
                "navigationBarTitleText": "消息"
            }
        },
        {
            "path": "pages/my/my",
            "style": {
                "navigationBarTitleText": "我的"
            }
        },
        {
            "path": "pages/signin/signin",
            "style": {}
        },
        {
            "path": "pages/write/write",
            "style": {}
        },
        {
            "path": "pages/info/info",
            "style": {}
        },
        {
            "path": "pages/setting/setting",
            "style": {}
        },
        {
            "path": "pages/user_info/user_info",
            "style": {}
        },
        {
            "path": "pages/user_name/user_name",
            "style": {}
        },
        {
            "path": "pages/register/register",
            "style": {}
        },
        {
            "path": "pages/password/password",
            "style": {}
        },
        {
            "path":"pages/article_detail/article_detail",
            "style":{}
        }
    ],
    "globalStyle": {
        "navigationBarTextStyle": "black",
        // "navigationBarTitleText" : "简阅",
        "navigationBarBackgroundColor": "#F8F8F8",
        "backgroundColor": "#F8F8F8"
    },
    "tabBar": {
        "color": "#707070",
        "selectedColor": "#DE533A",
        "list": [{
                "pagePath": "pages/index/index",
                "text": "文章",
                "iconPath": "static/nav1.png",
                "selectedIconPath": "static/nav1-a.png"
            },
            {
                "pagePath": "pages/message/message",
                "text": "消息",
                "iconPath": "static/nav2.png",
                "selectedIconPath": "static/nav2-a.png"
            },
            {
                "pagePath": "pages/my/my",
                "text": "我的",
                "iconPath": "static/nav3.png",
                "selectedIconPath": "static/nav3-a.png"
            }
        ]
    }
}
  • style的全局样式:
*{
    font-size: 14pt;
}
.container {
    width: 95%;
    margin: 0 auto;
}
.avatar {
    width: 60px;
    height: 60px;
    border-radius: 50%;
}
.list {
    display: flex;
    flex-direction: column;
}
.list-item {
    width: 100%;
    height: 40px;
    background-color: #fff;
    border-bottom: 1px solid #eee;
}
  • App.vue引入全局样式:
<style>
     @import 'style/style.css';
</style>
  • my.vue
<template>
    <view class="container">
        <!-- 顶部头像和昵称区域,纵向排列 -->
        <view class="top">
            <view class="avatar-box">
                <image src="../../static/default.png" mode="scaleToFill" class="avatar" v-if="!storageData.login"></image>
                <image :src="storageData.avatar" mode="scaleToFill" class="avatar" v-if="storageData.login"></image>
            </view>
            <view class="info-box">
                <navigator url="../signin/signin" v-if="!storageData.login">点击登录</navigator>
                <text v-if="storageData.login">{{ storageData.nickname }}</text>
                <navigator url="../setting/setting" v-if="storageData.login"><text class="setting-txt">个人设置</text></navigator>
            </view>
        </view>

        <!-- 中间文章数量、好友数量、消息数量等统计区域,横向排列 -->
        <view>
            <scroll-view class="grace-tab-title grace-center" scroll-x="true" id="grace-tab-title" >
                <view
                    v-for="(cate, index) in categories"
                    :key="index"
                    :data-cateid="cate.cateid"
                    :data-index="index"
                    :class="[cateCurrentIndex == index ? 'grace-tab-current' : '']"
                    @tap="tabChange"
                >
                    {{ cate.name }}
                </view>
            </scroll-view>
            <view class="demo-content" v-if="storageData.login">
                <!-- 文章部分 -->
                <view class="content" v-if="cateCurrentIndex === 0">
                    <view class="list">
                        <view class="list-item" v-for="(article, index) in articles" :key="index">
                            <text @tap="gotoDetail(article.id)">{{ article.title }}</text>
                        </view>
                    </view>
                </view>
                <!-- 关注部分 -->
                <view class="content" v-if="cateCurrentIndex === 1">
                    <view class="list">
                        <view class="list-item" v-for="(follow, index) in follows" :key="index">
                            <image :src="follow.avatar" class="avatar small"></image>
                            <text style="margin-left: 20px;">{{ follow.nickname }}</text>
                        </view>
                    </view>
                </view>
                <!-- 喜欢部分 -->
                <view class="content" v-if="cateCurrentIndex === 2">
                    <view class="list">
                        <view class="list-item" v-for="(like, index) in likes" :key="index">
                            <image :src="like.title" class="title small"></image>
                            <text style="margin-left: 20px;">{{ like.createTime }}</text>
                        </view>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
var loginRes, _self;
export default {
    data() {
        return {
            storageData: {
                userId: 0,
                nickname: '',
                avatar: '',
                title:'',
                createTime:'',
                login: false
            },
            //分类信息
            categories: [{ cateid: 0, name: '文章' }, { cateid: 1, name: '关注' }, { cateid: 2, name: '喜欢' }],
            // 当前选择的分类
            cateCurrentIndex: 0,
            articles: [],
            follows: [],
            likes:[]
        };
    },
    onLoad: function() {},
    onShow: function() {
        var _this = this;
        const loginKey = uni.getStorageSync('login_key');
        if (loginKey) {
            this.storageData = {
                login: loginKey.login,
                nickname: loginKey.nickname,
                avatar: loginKey.avatar,
                userId: loginKey.userId,
                title:loginKey.title
            };
            uni.request({
                url: this.apiServer + '/article/user_count',
                method: 'GET',
                header: { 'content-type': 'application/x-www-form-urlencoded' },
                data: {
                    userId: this.storageData.userId
                },
                success: res => {
                    _this.articleCount = res.data.data;
                }
            });
            uni.request({
                url: this.apiServer + '/article/user',
                method: 'GET',
                header: { 'content-type': 'application/x-www-form-urlencoded' },
                data: {
                    userId: this.storageData.userId
                },
                success: res => {
                    _this.articles = res.data.data;
                }
            });
            uni.request({
                url: this.apiServer + '/follow/list',
                method: 'GET',
                header: { 'content-type': 'application/x-www-form-urlencoded' },
                data: {
                    fromUId: this.storageData.userId
                },
                success: res => {
                    _this.follows = res.data.data;
                }
            });
        } else {
            this.storageData = {
                login: false
            };
            uni.request({
                    url: this.apiServer + '/like/list',
                    method: 'GET',
                    header: { 'content-type': 'application/x-www-form-urlencoded' },
                    data: {
                        fromId: this.storageData.userId
                    },
                    success: res => {
                        _this.follows = res.data.data;
                    }
                });
            } 
    },
    methods: {
        tabChange: function(e) {
            // 选中的索引
            var index = e.currentTarget.dataset.index;
            // 具体的分类id
            var cateid = e.currentTarget.dataset.cateid;
            this.cateCurrentIndex = index;
            // 动态替换内容
            this.content = this.categories[index].name;
        },
        gotoDetail: function(aId) {
            uni.navigateTo({
                url: '../article_detail/article_detail?aId=' + aId + '&userId=' + this.storageData.userId
            });
        }
    }
};
</script>

<style scoped>
.top {
    display: flex;
    flex-direction: column;
    text-align: center;
    height: 100px;
    margin-top: 5px;
}
.avatar-box {
    flex: 1 1 30%;
}
.info-box {
    flex: 1 1 70%;
    display: flex;
    align-items: center;
    justify-content: center;
}
.setting-txt {
    color: #00b26a;
    margin-left: 15px;
}
.center {
    display: flex;
    justify-content: center;
}
.info {
    flex: 1 1 25%;
    display: flex;
    flex-direction: column;
    text-align: center;
    border-right: 1px solid #eee;
}
.title {
    font-size: 14pt;
}
.content {
    margin-top: 20px;
    display: flex;
}
.list-item image{
    width: 80upx;
    height: 80upx;
    margin-top: -20upx;
}
</style>
  • signin类
<template>
    <view class="uni-flex uni-column container">
        <input class="uni-input" type="number" placeholder="输入手机号" v-model="userDTO.mobile" required="required" />
        <input class="uni-input" password type="text" placeholder="输入密码" v-model="userDTO.password" required="required" />
        <button class="green-btn" @tap="signIn(userDTO)">登录</button>
        <view class="aaa">
            <navigator url="../register/register" class="nav">注册新账号</navigator>
            <navigator url="../index/index" class="nav">返回主页</navigator>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            userDTO: {
                mobile: '',
                password: ''
            }
        };
    },
    onLoad() {},
    methods: {
        signIn: function(userDTO) {
            var _this = this;
            uni.request({
                url: this.apiServer + '/user/sign_in',
                method: 'POST',
                data: {
                    mobile: userDTO.mobile,
                    password: userDTO.password
                },
                header: {
                    'content-type': 'application/json'
                },
                success: res => {
                    // console.log(res.data.data);
                    if (res.data.code == 0) {
                        //将用户数据记录在本地存储
                        uni.setStorageSync('login_key', {
                            userId: res.data.data.id,
                            nickname: res.data.data.nickname,
                            avatar: res.data.data.avatar,
                            token: res.data.data.token,
                            login: true
                        });
                        uni.showToast({
                            title: '登录成功'
                        });
                        uni.switchTab({
                            url: '../my/my'
                        });
                    }
                    //登录失败,弹出各种原因
                    else {
                        uni.showModal({
                            title: '提示',
                            content: res.data.msg
                        });
                    }
                }
            });
        }
    }
};
</script>

<style scoped>
.nav {
    color: #00b26a;
    padding-top:10upx;
    /* margin-top: 10upx; */
}
input{
    margin-top: 50upx;
}
.green-btn{
    background: rgb(65,168,99);
    color: #FFFFFF;
    /* height: 80upx; */
    text-align: center;
    }
.aaa{
    display: flex;
    justify-content: space-between;
}
</style>
  • setting.vue
<template>
    <view class="container">
        <view class="list">
            <view class="list-item"><text>文章推送</text></view>
            <view class="list-item"><text>新消息推送</text></view>
            <navigator url="../user_info/user_info">个人资料</navigator>
        </view>
        <button @tap="logout" class="green-btn">退出当前账号</button>
    </view>
</template>

<script>
export default {
    data() {
        return {};
    },
    onLoad() {
        uni.setNavigationBarTitle({
            title: '设置'
        });
    },
    methods: {
        logout: function() {
            console.log('log out');
            uni.removeStorageSync('login_key');
            uni.showToast({
                title: '已经退出当前账号'
            });
            uni.navigateBack();
        }
    }
};
</script>

<style scoped>
    .green-btn{
        margin-top: 20px;
        width: 80%;
        background: #00B26A;
        color: white;
    }
</style>

运行的结果:


68945836.png
68945838.png
68945839.png
68945841.png
68945845.png
68945846.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 211,817评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,329评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,354评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,498评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,600评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,829评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,979评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,722评论 0 266
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,189评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,519评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,654评论 1 340
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,329评论 4 330
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,940评论 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,762评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,993评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,382评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,543评论 2 349