VUE=== (3)

一、跨域问题

1.为什么会出现夸域问题

跨域原因: 出于浏览器的同源策略限制。同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说Web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。同源策略会阻止一个域的javascript脚本和另外一个域的内容进行交互。所谓同源(即指在同一个域)就是两个页面具有相同的协议(protocol),主机(host)和端口号(port)。

因为浏览的同源策略,所有浏览器都有自己的同源策略,为了web安全而设置的

2.什么是跨域

当一个请求的url的协议,域名,端口号 三个之间任意一个与当前页面的url不同就是跨域

3.ssm如何设置跨域

/**
 * @author zhangyifan
 * @version 8.0
 * @description:
 * @date 2021/12/10 14:56
 */
public class SimpleCORSFilter implements Filter {
    
    
    private boolean isCross = false;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    
    
        String isCrossStr = filterConfig.getInitParameter("IsCross");
        isCross = isCrossStr.equals("true") ? true : false;
        System.out.println(isCrossStr);  
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
    
    
            if (isCross) {
    
    
                HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
                HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
                //使用通配符 * 允许所有域名发起的跨域请求
                httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
                //允许访问的方式
                httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
                //表示每次异步请求都发起预检请求,也就是说,发送两次请求。 resp.addHeader("Access-Control-Max-Age", "1800"),表示隔30分钟才发起预检请求。也就是说,发送两次请求
                httpServletResponse.setHeader("Access-Control-Max-Age", "0");
                //允许携带的头
                httpServletResponse.setHeader("Access-Control-Allow-Headers",
                        "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");
                //是否允许后续请求携带认证信息(cookies),该值只能是true,否则不返回。这个是服务端下发到客户端的 response 中头部字段,意义是允许客户端携带验证信息,例如 cookie 之类的。
                httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
                //代表javascript和Ajax的跨域请求
                httpServletResponse.setHeader("XDomainRequestAllowed", "1");
            }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
    
    
        isCross = false;
    }
}

4.配置 (web。xml)

<!-- 跨域请求 -->
<filter>  
<filter-name>SimpleCORSFilter</filter-name> 
 <filter-class>com.aaa.ssm.filter.SimpleCORSFilter</filter-class>  
 <init-param>  
   <param-name>IsCross</param-name>  
     <param-value>true</param-value>  
     </init-param>
     </filter>
     <filter-mapping> 
      <filter-name>SimpleCORSFilter</filter-name>  
      <url-pattern>/*</url-pattern>
      </filter-mapping>

二、elementui使用

1.简介

Element,一套为开发者、设计师和产品经理准备的基于 Vue 2.0 的桌面端组件库

2.使用npm安装

安装成功后就会在node_modules里面可以找到

npm i element-ui -S
在这里插入图片描述

3.引入element

在mainjs中

import ElementUI from ‘element-ui’;
import ‘element-ui/lib/theme-chalk/index.css’;

Vue.use(ElementUI);

在这里插入图片描述

三、axios简介安装

1.简介

基于promise可以用于浏览器和node.js的网络请求库

  易用、简洁且高效的http库。   支持原始JS中的Promise,做异步请求数据工具。

2.安装

npm install --save axios
import axios from ‘axios’
//设置路径的默认前缀axios.defaults.baseURL=“http://localhost:8080”
//把axios挂载到vue对象Vue.prototype.$http=axios;

npm install axios
在这里插入图片描述
main.js
在这里插入图片描述

四、增删改查

完整版 .vue文件

<template>
  <div>
    <el-row>
      <el-col :span="4"> 
        <!--查询功能-->
        <el-input
          v-model="deptSearch.dname"
          placeholder="请输入部门名称"
        ></el-input>
      </el-col>
      <el-col :span="4">
        <!--查询功能-->
        <el-input
          v-model="deptSearch.loc"
          placeholder="请输入部门位置"
        ></el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" icon="el-icon-search" @click="searchData"
          >搜索</el-button
        >
        <el-button
          type="primary"
          icon="el-icon-circle-plus"
          @click="(dialogFormVisible = true), restForm()"
          >新增</el-button
        >
      </el-col>
      <el-col :span="12">&nbsp;</el-col>
    </el-row>

    <!--列表-->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="deptNo" label="部门编号" width="180">
      </el-table-column>
      <el-table-column prop="deptName" label="名称" width="180">
      </el-table-column>
      <el-table-column prop="loc" label="位置"> </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!--分頁-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[2, 5, 10, 20, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <!--添加弹出框-->
    <el-dialog title="部门添加" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="form">
        <input
          v-if="form.deptNo != ''"
          v-model="form.deptNo"
          prop="deptNo"
          style="diplay: none"
        />
        <el-form-item label="部门名称" prop="deptName">
          <el-input v-model="form.deptName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="位置" prop="loc">
          <el-input v-model="form.loc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" v-if="item === ''" @click="addData('form')"
          >确 定2</el-button
        >
        <el-button type="primary" v-else @click="update('form')"
          >确 定1</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
    
    
  props: {
    
    
    //注册属性 父传子 数据传递
  },
  data() {
    
    
    return {
    
    
      tableData: [],
      currentPage: 1, //当前页
      pageSize: 5, //每页显示数量
      total: 400, //要分页数据的总数量 从后台查询
      deptSearch: {
    
     dname: "", loc: "" }, //查询对象
      dialogFormVisible: false, //默认该对话框不显示   如果让显示改为true
      form: {
    
    },
      rules: {
    
    
        deptName: [
          {
    
     required: true, message: "请输入部门名称", trigger: "blur" },
          {
    
     min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        loc: [
          {
    
     required: true, message: "请输入活动名称", trigger: "blur" },
          {
    
     min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
      },
      item: "",
    }; //定义数据
  },
  created() {
    
    
    //created在模板渲染成html前调用,通常在这里初始化某些属性,然后再渲染视图
    //alert(1111);
    this.loadData();
  },
  methods: {
    
    
    //方法事件处理
    //封装一个通用请求并加载数据的方法
    loadData() {
    
    
      var _this = this;
      this.$http
        .post("/deptRest/queryAll", {
    
    
          pageNo: this.currentPage,
          pageSize: this.pageSize,
          deptName: this.deptSearch.dname,
          loc: this.deptSearch.loc,
        })
        .then(function (response) {
    
    
          console.log(response);
          //赋值给tableData展示数据
          _this.tableData = response.data.data.list;
          //赋值总条数,动态计算页数  计算总页数: total%pageSize==0?total/pageSize:total/pageSize+1
          _this.total = response.data.data.total;
          _this.restForm();
        })
        .catch(function (error) {
    
    
          console.log(error);
        });
    },
    //处理每页显示数量发生变化的方法
    handleSizeChange(val) {
    
    
      console.log(`每页 ${
      
      val}`);
      this.pageSize = val;
      this.loadData();
    },
    //处理页码发生变化的方法
    handleCurrentChange(val) {
    
    
      console.log(`当前页: ${
      
      val}`);
      this.currentPage = val;
      this.loadData();
    },
    //查询方法
    searchData() {
    
    
      this.currentPage = 1;
      this.loadData();
    },
    //清空表单
    restForm() {
    
    
      //表单数据清空
      this.form.deptName = "";
      this.form.loc = "";
      this.form.deptNo = "";
      this.item = "";
    },
    //处理编辑
    handleEdit(index, row) {
    
    
      var _this = this;
      console.log(index, row);
      this.item = row.deptNo;
      this.form = JSON.parse(JSON.stringify(row));
      // this.$set(this.addlistform,'from',
      // [row.deptNo,row.loc,row.deptName])
      _this.dialogFormVisible = true;
    },
    update(formName) {
    
    
      this.$refs[formName].validate((valid) => {
    
    
        if (valid) {
    
    
          //alert("submit!");
          var _this = this;
          this.$http
            .post("/deptRest/update", this.form)
            .then(function (response) {
    
    
              console.log(response);
              if (response.data.code == 200) {
    
    
                //关闭对话框
                _this.dialogFormVisible = false;
                //提示添加成功
                _this.$message({
    
    
                  message: response.data.msg,
                  type: "success",
                });
                //刷新数据
                _this.loadData();
              } else {
    
    
                _this.$message.error("错了哦,这是一条错误消息");
              }
            })
            .catch(function (error) {
    
    
              console.log(error);
            });
        } else {
    
    
          console.log("error submit!!");

          return false;
        }
      });
    },
    //处理删除
    handleDelete(index, row) {
    
    
      var _this = this;
      console.log(index, row);

      var id = row.deptNo;
      var datt = {
    
     deptId: "id", paramA: "删除" };
      var deptId = row.deptNo;
      var paramA = "删除";

      this.$http
        .delete("/deptRest/deleteById/" + deptId + "-" + paramA, {
    
    })
        .then(function (response) {
    
    
          console.log(response);
          if (response.data.code == 200) {
    
    
            //关闭对话框
            _this.dialogFormVisible = false;
            //提示添加成功
            _this.$message({
    
    
              message: response.data.msg,
              type: "success",
            });
            //刷新数据
            _this.loadData();
          } else {
    
    
            _this.$message.error("错了哦,这是一条错误消息");
          }
        });
      this.currentPage = 1;
      this.loadData();
    },

    //处理添加
    addData(formName) {
    
    
      var _this = this;
      this.$refs[formName].validate((valid) => {
    
    
        if (valid) {
    
    
          //alert("submit!");
          this.$http
            .put("/deptRest/add", this.form)
            .then(function (response) {
    
    
              console.log(response);
              if (response.data.code == 200) {
    
    
                //关闭对话框
                _this.dialogFormVisible = false;
                //提示添加成功
                _this.$message({
    
    
                  message: response.data.msg,
                  type: "success",
                });
                //刷新数据
                _this.loadData();
              } else {
    
    
                _this.$message.error("错了哦,这是一条错误消息");
              }
            })
            .catch(function (error) {
    
    
              console.log(error);
            });
        } else {
    
    
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
  components: {
    
    
    //组件注册
  },
};
</script>
<style>
</style>

1.部门分页查询

 //方法事件处理
    //封装一个通用请求并加载数据的方法
    loadData() {
    
    
      var _this = this;
      this.$http
        .post("/deptRest/queryAll", {
    
    
          pageNo: this.currentPage,
          pageSize: this.pageSize,
          deptName: this.deptSearch.dname,
          loc: this.deptSearch.loc,
        })
        .then(function (response) {
    
    
          console.log(response);
          //赋值给tableData展示数据
          _this.tableData = response.data.data.list;
          //赋值总条数,动态计算页数  计算总页数: total%pageSize==0?total/pageSize:total/pageSize+1
          _this.total = response.data.data.total;
          _this.restForm();
        })
        .catch(function (error) {
    
    
          console.log(error);
        });
    },
    //处理每页显示数量发生变化的方法
    handleSizeChange(val) {
    
    
      console.log(`每页 ${
      
      val}`);
      this.pageSize = val;
      this.loadData();
    },
    //处理页码发生变化的方法
    handleCurrentChange(val) {
    
    
      console.log(`当前页: ${
      
      val}`);
      this.currentPage = val;
      this.loadData();
    },
    //查询方法
    searchData() {
    
    
      this.currentPage = 1;
      this.loadData();
    },

2.删除

    //处理删除
    handleDelete(index, row) {
    
    
      var _this = this;
      console.log(index, row);
      var deptId = row.deptNo;
      var paramA = "删除";
      this.$http
        .delete("/deptRest/deleteById/" + deptId + "-" + paramA, {
    
    })
        .then(function (response) {
    
    
          console.log(response);
          if (response.data.code == 200) {
    
    
            //关闭对话框
            _this.dialogFormVisible = false;
            //提示添加成功
            _this.$message({
    
    
              message: response.data.msg,
              type: "success",
            });
            //刷新数据
            _this.loadData();
          } else {
    
    
            _this.$message.error("错了哦,这是一条错误消息");
          }
        });
      this.currentPage = 1;
      this.loadData();
    },

3.新增

  //处理添加
    addData(formName) {
    
    
      var _this = this;
      this.$refs[formName].validate((valid) => {
    
    
        if (valid) {
    
    
          //alert("submit!");
          this.$http
            .put("/deptRest/add", this.form)
            .then(function (response) {
    
    
              console.log(response);
              if (response.data.code == 200) {
    
    
                //关闭对话框
                _this.dialogFormVisible = false;
                //提示添加成功
                _this.$message({
    
    
                  message: response.data.msg,
                  type: "success",
                });
                //刷新数据
                _this.loadData();
              } else {
    
    
                _this.$message.error("错了哦,这是一条错误消息");
              }
            })
            .catch(function (error) {
    
    
              console.log(error);
            });
        } else {
    
    
          console.log("error submit!!");
          return false;
        }
      });
    },

4.修改

  //处理编辑点击
    handleEdit(index, row) {
    
    
      var _this = this;
      console.log(index, row);
      this.item = row.deptNo;
      this.form = JSON.parse(JSON.stringify(row));
      // this.$set(this.addlistform,'from',
      // [row.deptNo,row.loc,row.deptName])
      _this.dialogFormVisible = true;
    },
    update(formName) {
    
    
      this.$refs[formName].validate((valid) => {
    
    
        if (valid) {
    
    
          //alert("submit!");
          var _this = this;
          this.$http
            .post("/deptRest/update", this.form)
            .then(function (response) {
    
    
              console.log(response);
              if (response.data.code == 200) {
    
    
                //关闭对话框
                _this.dialogFormVisible = false;
                //提示添加成功
                _this.$message({
    
    
                  message: response.data.msg,
                  type: "success",
                });
                //刷新数据
                _this.loadData();
              } else {
    
    
                _this.$message.error("错了哦,这是一条错误消息");
              }
            })
            .catch(function (error) {
    
    
              console.log(error);
            });
        } else {
    
    
          console.log("error submit!!");

          return false;
        }
      });
    },

总结

猜你喜欢

转载自blog.csdn.net/qq_45438019/article/details/121848487