vue-cli+笔记+axios封装get和post+day0811

34 篇文章 0 订阅
10 篇文章 0 订阅

day0811

  • 后端变成8080

  • 前端变成80

  • 因为前端才是用户输入的端口

  • config/index.js 里面修改

  • elementui 表格

  • axios请求怎么传参数

  • axios请求get传参

  • 无参的情况下axios.get(地址)
    有参数: axios.get(地址,{params:{}})
    params对应的json就是我们要传入到后端的数据

  • .then{ res => {
    成功了干啥
    }}
    .catch(err => {
    失败了干啥
    })
    .finally( () => {
    无论成功或者失败都得干
    })

  • axios请求 post 传参方式

  • axios.post(地址,formData对象)

父子组件传值
  • 1、子组件修改父组件的数值,show

  • 父组件先把值绑定到子组件中
    :show.sync = “show”(父组件中写)
    子组件中调用的是 this. e m i t ( " u p d a t e : 数 据 名 " , f a l s e ) t h i s . emit("update:数据名",false) this. emit("update:",false)this.emit(“update:show”,false)

  • 2、子组件调用父组件的函数:
    父组件把 函数绑定到子组件中(通过事件) @getData=“getData()”
    @getData=“getData()”
    子组件来触发事件 this.$emit(‘getData’)

  • template自定义列的内容,prop里面放的是json里面的属性名字

  • scope表示携带者数据************

  • 父组件向子组件传值,例如父组件向子组件传递id

  • 1、父组件吧值绑定到子组件的某个属性上
    例如 :editid=“editid”
    子组件定义 props:[“数据名”]

2、子组件定义 props: [‘属性名’]
props: [‘editid’]

axiosutil.js,这里面封装了axios的get和post请求

import axios from 'axios'
axios.defaults.baseURL = 'http://localhost:8080'
import { Loading } from 'element-ui';
import { Message } from 'element-ui';

export default {

  get(url,callback,params = {}){
    const loading = Loading.service({
             lock: true,
             text: '数据加载中',
             spinner: 'el-icon-loading',
             background: 'rgba(255, 255, 255, 0.7)'
           })

    axios.get(url,{
      params: params,
      }).then(res => {

      if(res.data.code === 200){
          callback(res.data)
      }else {
           Message.error(res.data.message);
      }


    }).catch( err => {
      Message.error(err);
    }).finally(() => {
      loading.close()
    })
  },
   post(url,callback,params={}){


     const formData = new FormData()
     //循环的是json里面的key
     //拿着key的怎么去找value
     for(let key in params)
     {
         formData.append(key,params[key])
         console.log(key+'---------->'+ params[key])
     }

     const loading = Loading.service({
              lock: true,
              text: '数据提交中',
              spinner: 'el-icon-loading',
              background: 'rgba(255, 255, 255, 0.7)'
            })

     setTimeout(function(){
       loading.close()
     },5000)

     axios.post(url,formData)
     .then(res => {
       if(res.data.code === 200){
           Message.success(res.data.message)
           callback(res.data)
       }else {
          Message.error(res.data.message);
       }
     }).catch( err => {
      Message.error(err);
    }).finally(() => {
      loading.close()
    })

   }

}

view/user/index.vue

<template>

 <div>

    <el-row style="margin-bottom: 10px;">
      <el-col :span="6"><el-input v-model="search.username" placeholder="请输入查询的用户名"></el-input></el-col>
      <el-col :span="2"> <el-button type="primary" plain  @click="searchData()">查询</el-button></el-col>
      <el-col :span="2"> <el-button type="primary" plain  @click="addtest()">增加</el-button></el-col>
    </el-row>

    <el-table
       :data="result.tableData"
       style="width: 100%"
       >

       <el-table-column
         label="ID"
         width="180"
         prop = 'id'>
       </el-table-column>

       <el-table-column
         label="姓名"
         width="180"
         prop = 'username'>
       </el-table-column>

       <el-table-column
         label="密码"
         width="180"
         prop = 'password'>
       </el-table-column>

       <el-table-column label="操作">
         <template slot-scope="scope">
           <el-button
             size="mini"
             @click="handleEdit(scope.row.id)">编辑</el-button>
           <el-button
             size="mini"
             type="danger"
             @click="handleDelete(scope.$index, scope.row)">删除</el-button>
         </template>
       </el-table-column>
     </el-table>


     <el-pagination
     style="margin-top: 20px;"
       background
       layout="prev, pager, next"
       :page-count="result.pages"
       :current-page.sync="query.pageNo"
       :page-size="query.pageSize"
       @current-change="getData()"
       >
     </el-pagination>

     <el-dialog title="编辑用户信息" :visible.sync="show" :close-on-click-modal="false">
        <UserEdit v-if="show"
         :show.sync="show"
          @getData="getData()"
          :editid = "editid"
           ></UserEdit>
     </el-dialog>

 </div>

</template>

<script>
 import UserEdit from '@/views/user/edit'
  export default {
    name: 'User',
    data(){
      return {
      search: {
         username: ''
      },
       query: {
         username: '',
         pageNo: 1,
         pageSize: 7
       },
       result: {
          tableData: [],
           pages: 0
       },
       show: false,
       editid: null
      }
    },
    components: {
      UserEdit
    },
    created() {
      this.getData()
    },
    methods: {
      getData() {
        this.axios.get('/user/list',res => {
            this.result.tableData = res.obj.records
            this.result.pages = res.obj.pages
        },this.query)
      },
      searchData(){
        this.query.username = this.search.username
        this.query.pageNo =1
        this.getData()
      },
      handleEdit(id){
        this.editid = id
        this.show = true
      },
      addtest(){
        this.editid = null
        this.show = true
      }
    }
  }
</script>

<style>
</style>

user/edit.vue

<template>
  <div>
    <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.password"></el-input>
        </el-form-item>

         <el-form-item >
            <el-button type="primary" plain @click="save()">保存数据</el-button>
         </el-form-item>
    </el-form>
  </div>
</template>

<script>
  export default {
    name: 'UserEdit',
    props: ['editid'],
    data(){
      return {
        form: {
          username: '',
          password: ''
        }
      }
    },
    created() {
      if(this.editid){
       //通过Id读取原始数据
        this.axios.get("/user/getById", res => {
            this.form = res.obj
        }, {id: this.editid})
      }
    },
    methods: {
      save() {
        this.axios.post('/user/save',res => {
          //子组件要修改父组件的数值,修改父组件的show值
          this.$emit('update:show',false)
          this.$emit('getData')
        },this.form)
      }
    }
  }
</script>

<style>
</style>

userService.java中的条件查询

package com.neuedu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neuedu.pojo.User;
import com.neuedu.dao.UserMapper;
import com.neuedu.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liuyong
 * @since 2020-08-10
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

//    @Override
//    public IPage<User> page(User user) {
//        //
//
//        IPage<User> query = new Page<>(user.getPageNo(),user.getPageSize());
//        return page(query);
//    }

    @Override
    public IPage<User> page(User user) {
        //如果user对象中username有数值,就按照条件查询了
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(user.getUsername())){
            queryWrapper.like("username",user.getUsername());
        }
        IPage<User> query = new Page<>(user.getPageNo(),user.getPageSize());
        return page(query,queryWrapper);

    }
}

ResultCode.enum

package com.neuedu.pojo;

        import javax.annotation.Resource;

public enum ResultCode {
    SUCCESS(200,"操作成功")
    ,FAILED(500,"操作失败")
    ,NOTOKEN(401,"未登录或者登陆超时")
    ,NOPREMISS(403,"没有权限");

    private Integer code;
    private String message;

    private ResultCode(Integer code, String message) {
        this.code = code;
        this.message = message;
    }

    private ResultCode() {
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

封装的通用查询结果 CommonResult.java

package com.neuedu.pojo;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

/**
 *
 * 统一返回类型
 *
 * */

@Getter
//相当于只生成了get方法
public class CommonResult {

    //状态码,是否成功执行的标志
    private Integer code;
    //业务模块需要的数据
    private Object obj;
    //消息,添加成功
    private String message;

    private CommonResult(){}

    private CommonResult(Integer code, Object obj, String message) {
        this.code = code;
        this.obj = obj;
        this.message = message;
    }




    //状态码不要胡写,规范一下,建立一个枚举
    public  static  CommonResult getInstance(Integer code, Object obj, String msg){
        return new CommonResult(code,obj,msg);
    }


    //状态码不要胡写,规范一下,建立一个枚举
    public  static  CommonResult getInstance(ResultCode resultCode, String message){
        return new CommonResult(resultCode.getCode(),null,message);
    }




    public static CommonResult success(Object obj){
        return new CommonResult(ResultCode.SUCCESS.getCode(),obj,ResultCode.SUCCESS.getMessage());

    }

    public static CommonResult fail(){
        return new CommonResult(ResultCode.FAILED.getCode(),null,ResultCode.FAILED.getMessage());

    }


    public static CommonResult fail(String message){
        return new CommonResult(ResultCode.FAILED.getCode(),null,message);

    }


    public static CommonResult notoken(){
        return new CommonResult(ResultCode.NOTOKEN.getCode(),null,ResultCode.NOTOKEN.getMessage());

    }


    public static CommonResult nopremiss(){
        return new CommonResult(ResultCode.NOPREMISS.getCode(),null,ResultCode.NOPREMISS.getMessage());

    }


}

test/com/neuedu/utils/Auto.java 通用的代码生成器

package com.neuedu.utils;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.ArrayList;
import java.util.List;

public class Auto {
    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");//生成的具体位置
        gc.setAuthor("liuyong");//所有者
        gc.setOpen(false);
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        //配置一下连接,读数据库的表
        dsc.setUrl("jdbc:mysql://localhost:3306/db1?useUnicode=true&useSSL=false&characterEncoding=utf8");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("1234");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        //pc.setModuleName(scanner("模块名"));
        pc.setParent("com.neuedu");
        pc.setEntity("pojo");
        pc.setMapper("dao");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setController("controller");

        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        // 如果模板引擎是 velocity
        // String templatePath = "/templates/mapper.xml.vm";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名  如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                return projectPath + "/src/main/resources/com/neuedu/dao"
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        /*
        cfg.setFileCreate(new IFileCreate() {
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                // 判断自定义文件夹是否需要创建
                checkDir("调用默认方法创建的目录,自定义目录用");
                if (fileType == FileType.MAPPER) {
                    // 已经生成 mapper 文件判断存在,不想重新生成返回 false
                    return !new File(filePath).exists();
                }
                // 允许生成模板文件
                return true;
            }
        });
        */
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        // templateConfig.setEntity("templates/entity2.java");
        // templateConfig.setService();
        // templateConfig.setController();

        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setSuperEntityClass("com.neuedu.pojo.BaseEntry");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // 公共父类
        //strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
        // 写于父类中的公共字段
        strategy.setSuperEntityColumns("id");
        //生成的表名,什么都不写,就给你生成数据库中的所有的表的名字
        strategy.setInclude("user");
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}

BaseEntry.java 代码生成器继承的父类

package com.neuedu.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor

public class BaseEntry {
    //让Mybatis知道id是自增长的
    @TableId(type = IdType.AUTO)
    private Integer id;
    //这个不属于表中的字段
    @TableField(exist = false)
    @JsonIgnore
    private  Integer pageNo= 1;
    @TableField(exist = false)
    @JsonIgnore
    private  Integer pageSize = 6;
    @TableField(exist = false)
    @JsonIgnore
    //@JsonIgnore是不在序列化,就是不显示
    private  Integer withPage = 1;
}

config/BaseConfig.java 这个是bean节点注入

package com.neuedu.config;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class BaseConfig {

    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        // 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求  默认false
        // paginationInterceptor.setOverflow(false);
        // 设置最大单页限制数量,默认 500 条,-1 不受限制
        // paginationInterceptor.setLimit(500);
        // 开启 count  join 优化,只针对部分 left join
        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
        return paginationInterceptor;
    }

    @Bean
    CorsFilter cors(){
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.addAllowedHeader("*");
        configuration.addAllowedOrigin("*");
        configuration.addAllowedMethod("*");
        source.registerCorsConfiguration("/**",configuration);
        return  new CorsFilter(source);
    }
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值