20230708----重返学习-通用物模型基础样式

day-108-one-hundred-and-eight-20230708-通用物模型基础样式

通用物模型

通用物模型基础

  1. 先扒接口。
  2. 相关接口写在一起。
  3. 对一些数据进行缓存,如果是接口的,也可以改造接口让其可以把数据存储在本地。
相关接口分模块
  • 核心代码:

    • fang/f20230708/ManageSystem/src/api/iot.js

      import http from "./http";
      
      // 获取物模型类别信息。
      /* //物模型类别-get
      /system/dict/data/type/iot_things_type
      */
      const queryIotThingsType = () => http.get(`/system/dict/data/type/iot_things_type`);
      
      export default {
        queryIotThingsType,
      };
      
    • fang/f20230708/ManageSystem/src/api/index.js

      import iot from "./iot";
      
      /* 暴露API */
      const API = {
        iot, //this.$API.ito.xxxx来调用。
      };
      export default API;
      
  • 代码:

    • fang/f20230708/ManageSystem/src/api/iot.js

      import http from "./http";
      import store from "@/store";
      import ut from "@/assets/utils";
      
      // 获取物模型类别信息。
      /* //物模型类别-get
      /system/dict/data/type/iot_things_type
      */
      const queryIotThingsType = async () => {
        let cache = ut.storage.get("cache_iot_things_type");
        if (cache) {
          return cache;
        }
      
        //没有缓存,向服务器发送请求。
        let arr = [];
        try {
          let { code, data } = await http.get(
            `/system/dict/data/type/iot_things_type`
          );
          if (+code === 200) {
            //把服务器返回的数据变为自己需要的。
            arr = data.map((item) => {
              return {
                lable: item.dictLabel,
                value: item.dictValue,
                class: item.listClass,
              };
            });
          }
      
          //把处理后的数据缓存到本地。
          ut.storage.set("cache_iot_things_type", arr);
        } catch (error) {
          console.log(`error:-->`, error);
        }
        return arr;
      };
      
      //获取物模型列表信息。
      /* //物模型数据类别-get
      /system/dict/data/type/iot_data_type
      */
      const queryIotDataType = async () => {
        let cache = ut.storage.get("cache_iot_data_type");
        if (cache) {
          return cache;
        }
      
        let arr = [];
        try {
          let { code, data } = await http.get(`/system/dict/data/type/iot_data_type`);
          if (+code === 200) {
            arr = data.map(({ dictLabel, dictValue }) => {
              return {
                lable: dictLabel,
                value: dictValue,
              };
            });
            //存储到本地。
            ut.storage.set("cache_iot_data_type", arr);
          }
        } catch (error) {
          console.log(`error:-->`, error);
        }
        return arr;
      };
      
      // 获取物模型列表信息-支持分页和搜索。
      /* //物模型列表信息-get
      /iot/template/list
      传参
      pageNum=1
      pageSize=10
      templateName: aaa  按名字搜索
      type: 2  物模型类别
      */
      const queryTemplateList = (obj) => {
        let { pageNum, pageSize, templateName, type } = obj;
        let params = {
          pageNum, //当前页数。
          pageSize, //一页多少条。
        };
        if (typeof templateName !== "undefined") {
          params.templateName = templateName; //按物模型名字搜索
        }
        if (typeof type !== "undefined") {
          params.type = type; //物模型类别
        }
        return http.get(`/iot/template/list`, {
          params,
        });
      };
      
      // 获取指定物模型的详细信息。
      /* //获取某一条物模型的详细信息
      /iot/template/578
      */
      const queryTemplateInfo = (templateId) =>
        http.get(`/iot/template/${templateId}`);
      
      // 新增物模型的信息。
      /* //新增物模型信息
      /iot/template 「POST」
      传参
      {"templateId":null,"templateName":"dsadasdsad","userId":null,"userName":null,"tenantId":null,"tenantName":null,"identifier":"aaaaaaaaa","modelOrder":0,"type":"2","datatype":"decimal","isSys":null,"isChart":0,"isHistory":1,"isMonitor":0,"isReadonly":1,"delFlag":null,"createBy":"fastbee","createTime":null,"updateBy":null,"updateTime":null,"remark":null,"specs":"{\"type\":\"decimal\",\"min\":12,\"max\":200,\"unit\":\"千米\",\"step\":10}"}
      */
      const _TemplateParams = {
        templateName: "",
        identifier: "",
        modelOrder: 0,
        type: 1,
        datatype: "integer",
        isChart: 0,
        isHistory: 0,
        isMonitor: 0,
        isReadonly: 0,
        specs: "",
      
        templateId: null,
        userId: null,
        userName: null,
        tenantId: null,
        tenantName: null,
        isSys: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      const insertTemplateInfo = (obj) => {
        let params = Object.assign({}, _TemplateParams, obj);
        params.createBy = store.state?.profile?.user?.userName || null; //在调用时,获取登录者信息的名称。
        return http.post("/iot/template", obj);
      };
      
      // 修改物模型接口-这里没有测试和遇到过,自己猜的。
      const updateTemplateInfo = (obj) => {
        //相比较于新增,obj中需要多传递一个templateId。
        let params = Object.assign({}, _TemplateParams, obj);
        params.createBy = store.state?.profile?.user?.userName || null; //在调用时,获取登录者信息的名称。
        return http.put("/iot/template", obj);
      };
      
      // 删除物模型接口-这里没有测试和遇到过,自己猜的。
      const deleteTemplateInfo = (ids) => {
        if (!Array.isArray(ids)) {
          ids = [ids];
        }
      
        return http.delete("/iot/template", {
          data: {
            ids,
          },
        });
      };
      export default {
        queryIotThingsType,
        queryIotDataType,
        queryTemplateList,
      
        queryTemplateInfo,
        insertTemplateInfo,
        updateTemplateInfo,
        deleteTemplateInfo,
      };
      
    • fang/f20230708/ManageSystem/src/api/index.js

      import http from "./http";
      
      import iot from "./iot";
      
      // 获取验证码
      const queryCaptchaImage = () => http.get("/captchaImage");
      
      // 用户登录校验
      const checkUserLogin = (body) => http.post("/login", body);
      
      // 获取登录者信息「含权限信息」
      const queryUserProfile = () => http.get("/getInfo");
      
      // 获取地图标注数据
      const queryDeviceAll = () => http.get("/iot/device/all");
      
      /* 暴露API */
      const API = {
        iot, //this.$API.ito.xxxx来调用。
        queryCaptchaImage,
        checkUserLogin,
        queryUserProfile,
        queryDeviceAll,
      };
      export default API;
      
    • fang/f20230708/ManageSystem/src/layout/HeaderLayout.vue

      <script>
      import { mapState, mapMutations } from "vuex";
      import NavLayout from "./NavLayout.vue";
      import ut from "@/assets/utils";
      
      export default {
        components: {
          NavLayout,
        },
        props: {
          collapsed: Boolean,
        },
        computed: {
          // 把vuex中的部分公共状态获取使用
          ...mapState(["profile"]),
          // 获取面包屑导航的数据
          breadcrumbList() {
            let route = this.$route,
              routeList = this.$router.getRoutes();
            let arr = [],
              match = routeList.find((item) => item.path === route.path);
            while (match) {
              let {
                path,
                meta: { title },
              } = match;
              if (title) {
                arr.unshift({
                  path,
                  title,
                });
              }
              match = match.parent;
            }
            return arr;
          },
        },
        methods: {
          ...mapMutations(["setProfile"]),
          handleCommand(command) {
            if (command === "logout") {
              // 退出登录:清除Token、清除登录者信息、提示、跳转
              ut.storage.remove("TK");
              this.setProfile(null);
              // ...
              this.$message.success("您已安全退出");
              this.$router.replace({
                path: "/user/login",
                query: {
                  target: this.$route.fullPath,
                },
              });
              return;
            }
            // 路由跳转
            this.$router.push(command);
          },
      
          //强制更新:清除部分本地存储信息&强制刷新。
          refresh() {
            console.log(`refresh-->`);
            //缓存的东西在本地存储的localStorage及sessionStorage或cookie里看,然后做循环进行删除。
            ["cache_iot_things_type","cache_iot_data_type"].forEach(key=>{
              localStorage.removeItem(key)
            })
      
            location.reload(); //刷新页面。
          },
        },
      };
      </script>
      
      <template>
        <header class="header-layout">
          <div class="content">
            <div class="left">
              <i
                class="el-icon-s-unfold"
                @click="$emit('update:collapsed', false)"
                v-if="collapsed"
              ></i>
              <i
                class="el-icon-s-fold"
                @click="$emit('update:collapsed', true)"
                v-else
              ></i>
              <el-breadcrumb>
                <el-breadcrumb-item
                  v-for="item in breadcrumbList"
                  :key="item.path"
                  :to="item.path"
                >
                  {{ item.title }}
                </el-breadcrumb-item>
              </el-breadcrumb>
            </div>
            <div class="right">
              <el-tooltip content="清空全部缓存及强制刷新">
                <i class="el-icon-refresh" @click="refresh"></i>
              </el-tooltip>
              <el-dropdown @command="handleCommand" v-if="profile">
                <span class="account-avatar">
                  <el-avatar :src="mixinPrefixAdd(profile.user.avatar)" />
                  <span>{{ profile.user.nickName }}</span>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="/index/personal" icon="el-icon-user">
                    个人中心
                  </el-dropdown-item>
                  <el-dropdown-item command="/index/setting" icon="el-icon-setting">
                    个人设置
                  </el-dropdown-item>
                  <el-dropdown-item command="logout" icon="el-icon-position" divided>
                    退出登录
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </div>
          <div class="nav scrollActive">
            <NavLayout />
          </div>
        </header>
      </template>
      
      <style lang="less" scoped>
      .header-layout {
        padding: 0;
        height: 80px;
        background-color: #fff;
      
        .content,
        .nav {
          box-sizing: border-box;
          overflow: hidden;
        }
      
        .content {
          padding: 0 15px;
          height: 50px;
          line-height: 50px;
          box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
          display: flex;
          justify-content: space-between;
          align-items: center;
      
          .left {
            display: flex;
            align-items: center;
      
            .el-icon-s-fold,
            .el-icon-s-unfold {
              font-size: 18px;
              margin-right: 20px;
            }
          }
      
          .right {
            display: flex;
            align-items: center;
      
            .el-tooltip {
              font-size: 25px;
              margin-right: 15px;
              cursor: pointer;
            }
      
            .account-avatar {
              display: flex;
              align-items: center;
      
              .el-avatar {
                margin-right: 5px;
                width: 30px;
                height: 30px;
              }
      
              :deep(.el-avatar--circle) {
                border-radius: 50% !important;
              }
      
              span {
                max-width: 132px;
                text-overflow: ellipsis;
                white-space: nowrap;
                overflow: hidden;
              }
            }
          }
        }
      
        .nav {
          margin: 0 15px;
          padding-top: 2px;
          height: 30px;
          overflow-x: auto;
        }
      }
      </style>
      
无需参数get请求
  • fang/f20230708/ManageSystem/src/api/iot.js
// 获取物模型类别信息。
/* //物模型类别-get
/system/dict/data/type/iot_things_type
 */
const queryIotThingsType = () =>
  http.get(`/system/dict/data/type/iot_things_type`);
动态参数get请求
  • fang/f20230708/ManageSystem/src/api/iot.js
// 获取物模型列表信息-支持分页和搜索。
/* //物模型列表信息-get
/iot/template/list
传参
pageNum=1
pageSize=10
templateName: aaa  按名字搜索
type: 2  物模型类别
 */
const queryTemplateList = (obj) => {
  let { pageNum, pageSize, templateName, type } = obj;
  let params = {
    pageNum,//当前页数。
    pageSize,//一页多少条。
  };
  if (typeof templateName !== "undefined") {
    params.templateName = templateName;//按物模型名字搜索
  }
  if (typeof type !== "undefined") {
    params.type = type;//物模型类别
  }
  return http.get(`/iot/template/list`, {
    params,
  });
};
有默认值且需要合并的接口
  1. 默认值写在接口外部,后面要用时,合并一下对象。
    • 需要传与不需要传的可以分类排放。
  • fang/f20230708/ManageSystem/src/api/iot.js
import http from "./http";
import store from "@/store";
// 新增物模型的信息。
/* //新增物模型信息
/iot/template 「POST」
传参
{"templateId":null,"templateName":"dsadasdsad","userId":null,"userName":null,"tenantId":null,"tenantName":null,"identifier":"aaaaaaaaa","modelOrder":0,"type":"2","datatype":"decimal","isSys":null,"isChart":0,"isHistory":1,"isMonitor":0,"isReadonly":1,"delFlag":null,"createBy":"fastbee","createTime":null,"updateBy":null,"updateTime":null,"remark":null,"specs":"{\"type\":\"decimal\",\"min\":12,\"max\":200,\"unit\":\"千米\",\"step\":10}"}
 */
const _TemplateParams = {
  templateName: "",
  identifier: "",
  modelOrder: 0,
  type: 1,
  datatype: "integer",
  isChart: 0,
  isHistory: 0,
  isMonitor: 0,
  isReadonly: 0,
  specs: "",

  templateId: null,
  userId: null,
  userName: null,
  tenantId: null,
  tenantName: null,
  isSys: null,
  delFlag: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  remark: null,
};
const insertTemplateInfo = (obj) => {
  let params = Object.assign({}, _TemplateParams, obj);
  params.createBy = store.state?.profile?.user?.userName || null; //在调用时,获取登录者信息的名称。
  return http.post("/iot/template", obj);
};
  • 在调用时,获取登录者信息的名称。
import http from "./http";
import store from "@/store";
const _TemplateParams = {
  createBy: null,
};
const insertTemplateInfo = (obj) => {
  let params = Object.assign({}, _TemplateParams, obj);
  params.createBy = store.state?.profile?.user?.userName || null; //在调用时,获取登录者信息的名称。
  return http.post("/iot/template", obj);
};
放在路径上的信息
// 获取指定物模型的详细信息。
/* //获取某一条物模型的详细信息
/iot/template/578
 */
const queryTemplateInfo = templateId =>http.get(`/iot/template/${templateId}`)

数据缓存

  1. 有些数据不怎么变动,可以存储到本地localhost上,或者是vuex上。
    • 不过需要配合本地强制刷新功能的代码,否则这些数据都不会变,会导致数据万年不变的。
  2. 具体步骤就是
  • 示例代码:
    • fang/f20230708/ManageSystem/src/api/iot.js 仅本地做缓存

      // 获取物模型类别信息。
      /* //物模型类别-get
      /system/dict/data/type/iot_things_type
      */
      const queryIotThingsType = async () => {
        let cache = JSON.parse(localStorage.getItem("cache_iot_things_type"));
        
        if (cache) {
          return cache;
        }
      
        //没有缓存,向服务器发送请求。
        let arr = [];
        try {
          let { code, data } = await http.get(`/system/dict/data/type/iot_things_type`);
          if (+code === 200) {
            //把服务器返回的数据变为自己需要的。
            arr = data
      
      
            //把处理后的数据缓存到本地。
            localStorage.setItem("cache_iot_things_type",JSON.stringify(arr) );
          }
      
        } catch (error) {
          console.log(`error:-->`, error);
        }
        return arr;
      };
      
      // 获取物模型类别信息。
      /* //物模型类别-get
      /system/dict/data/type/iot_things_type
      */
      const queryIotThingsType = async () => {
        let cache = ut.storage.get("cache_iot_things_type");
        if (cache) {
          return cache;
        }
      
        //没有缓存,向服务器发送请求。
        let arr = [];
        try {
          let { code, data } = await http.get(
            `/system/dict/data/type/iot_things_type`
          );
          if (+code === 200) {
            //把服务器返回的数据变为自己需要的。
            arr = data.map((item) => {
              return {
                lable: item.dictLabel,
                value: item.dictValue,
                class: item.listClass,
              };
            });
          }
      
          //把处理后的数据缓存到本地。
          ut.storage.set("cache_iot_things_type", arr);
        } catch (error) {
          console.log(`error:-->`, error);
        }
        return arr;
      };
      
    • fang/f20230708/ManageSystem/src/layout/HeaderLayout.vue 做数据强制更新。

      <script>
      export default {
        methods: {
      
          //强制更新:清除部分本地存储信息&强制刷新。
          refresh() {
            console.log(`refresh-->`);
            //缓存的东西在本地存储的localStorage及sessionStorage或cookie里看,然后做循环进行删除。
            ["cache_iot_things_type","cache_iot_data_type"].forEach(key=>{
              localStorage.removeItem(key)
            })
      
            location.reload(); //刷新页面。
          },
        },
      };
      </script>
      
      <template>
              <el-tooltip content="清空全部缓存及强制刷新">
                <i class="el-icon-refresh" @click="refresh"></i>
              </el-tooltip>
      </template>
      
      <style lang="less" scoped>
            .el-tooltip {
              font-size: 25px;
              margin-right: 15px;
              cursor: pointer;
            }
      </style>
      
接口直接处理后端数据变成前端想要的
  • fang/f20230708/ManageSystem/src/api/iot.js
// 获取物模型类别信息。
/* //物模型类别-get
/system/dict/data/type/iot_things_type
 */
const queryIotThingsType = async () => {
  let arr = [];
  try {
    let { code, data } = await http.get(
      `/system/dict/data/type/iot_things_type`
    );
    if (+code === 200) {
      //把服务器返回的数据变为自己需要的。
      arr = data.map((item) => {
        return {
          lable: item.dictLabel,
          value: item.dictValue,
          class: item.listClass,
        };
      });
    }
  } catch (error) {
    console.log(`error:-->`, error);
  }
  return arr
};

页面数据强制刷新

  1. 在函数执行时,先清除本地缓存的信息。而浏览器能进行长期存储的,一般也就用localStorage及sessionStorage或cookie,数据库这一类的,一般不常用。
    • 这一步主要就是把在刷新页面时还保留的数据给手动移除。
    • vuex的持久化存储,一般也是依赖的localStorage这类本地存储。
    • 可以对localStorage这类本地存储做一个循环,如果有需要,还可以都清除内部存储的所有东西。
    • 可以允许一些本地存储数据依旧保留,如token等。
  2. 第一步完成之后,使用location.reload()来刷新页面。
    • 这一步就是刷新页面,让vuex中没做持久化的数据初始化。
    • 也可以对一些全局变量做初始化。
  • fang/f20230708/ManageSystem/src/layout/HeaderLayout.vue

    <script>
    export default {
      methods: {
    
        //强制更新:清除部分本地存储信息&强制刷新。
        refresh() {
          console.log(`refresh-->`);
          //缓存的东西在本地存储的localStorage及sessionStorage或cookie里看,然后做循环进行删除。
          ["cache_iot_things_type","cache_iot_data_type"].forEach(key=>{
            localStorage.removeItem(key)
          })
    
          location.reload(); //刷新页面。
        },
      },
    };
    </script>
    
    <template>
            <el-tooltip content="清空全部缓存及强制刷新">
              <i class="el-icon-refresh" @click="refresh"></i>
            </el-tooltip>
    </template>
    
    <style lang="less" scoped>
          .el-tooltip {
            font-size: 25px;
            margin-right: 15px;
            cursor: pointer;
          }
    </style>
    

通用物模型增删改查

绑定查询框
<script>
export default {
  data() {
    return {
      // 相关类别的全部数据。
      iotThingsList: [],
      iotDataList: [],

      //筛选区域需要的状态。
      filter: {
        templateName: "",
        type: "",
      },

      //分页相关的状态。
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
    };
  },
};
</script>

<template>
  <div class="template-box">
    <!-- 筛选/操作区域 -->
    <div class="filter-box">
      <div class="filter">
        <div class="form-item">
          <label>名称</label>
          <el-input
            placeholder="请输入物模型名称"
            v-model.trim="filter.templateName"
            @keydown.native.enter="initData"
          />
        </div>
        <div class="form-item">
          <label>类别</label>
          <el-select v-model="filter.type" @change="initData">
            <el-option value="" label="全部" />
            <el-option
              v-for="item in iotThingsList"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            />
          </el-select>
        </div>
      </div>
    </div>
  </div>
</template>
摁回车加原生事件
<script>
export default {
  data() {
    return {
      //筛选区域需要的状态。
      filter: {
        templateName: "",
        type: "",
      },

      //分页相关的状态。
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
    };
  },
  methods: {
    //获取物模型列表数据。
    async initData() {
      //   console.log(`initData-->`);
      let {
        page: { pageNum, pageSize },
        filter: { templateName, type },
      } = this;
      try {
        let { code } = await this.$API.iot.queryTemplateList({
          pageNum,
          pageSize,
          templateName,
          type,
        });
      } catch (error) {
        console.log(`error:-->`, error);
      }
    },
  },
};
</script>

<template>
  <el-input
    placeholder="请输入物模型名称"
    v-model.trim="filter.templateName"
    @keydown.native.enter="initData"
  />
</template>
初始化并行请求
  1. 用Object.freeze()把不需要响应式的数据冻结起来,提高性能。
  • fang/f20230708/ManageSystem/src/api/iot.js
import http from "./http";
import store from "@/store";
import ut from "@/assets/utils";

// 获取物模型类别信息。
/* //物模型类别-get
/system/dict/data/type/iot_things_type
 */
const queryIotThingsType = async () => {
  let cache = ut.storage.get("cache_iot_things_type");
  if (cache) {
    return cache;
  }

  //没有缓存,向服务器发送请求。
  let arr = [];
  try {
    let { code, data } = await http.get(
      `/system/dict/data/type/iot_things_type`
    );
    if (+code === 200) {
      //把服务器返回的数据变为自己需要的。
      arr = data.map((item) => {
        return {
          label: item.dictLabel,
          value: item.dictValue,
          class: item.listClass,
        };
      });
    }

    //把处理后的数据缓存到本地。
    ut.storage.set("cache_iot_things_type", arr);
  } catch (error) {
    console.log(`error:-->`, error);
  }
  return arr;
};

//获取物模型列表信息。
/* //物模型数据类别-get
/system/dict/data/type/iot_data_type
 */
const queryIotDataType = async () => {
  let cache = ut.storage.get("cache_iot_data_type");
  if (cache) {
    return cache;
  }

  let arr = [];
  try {
    let { code, data } = await http.get(`/system/dict/data/type/iot_data_type`);
    if (+code === 200) {
      arr = data.map(({ dictLabel, dictValue }) => {
        return {
          label: dictLabel,
          value: dictValue,
        };
      });
      //存储到本地。
      ut.storage.set("cache_iot_data_type", arr);
    }
  } catch (error) {
    console.log(`error:-->`, error);
  }
  return arr;
};

// 获取物模型列表信息-支持分页和搜索。
/* //物模型列表信息-get
/iot/template/list
传参
pageNum=1
pageSize=10
templateName: aaa  按名字搜索
type: 2  物模型类别
 */
const queryTemplateList = (obj) => {
  let { pageNum, pageSize, templateName, type } = obj;
  let params = {
    pageNum, //当前页数。
    pageSize, //一页多少条。
  };
  if (templateName) {
    params.templateName = templateName; //按物模型名字搜索
  }
  if (type) {
    params.type = type; //物模型类别
  }
  return http.get(`/iot/template/list`, {
    params,
  });
};
export default {
  queryIotThingsType,
  queryIotDataType,
  queryTemplateList,
};
  • fang/f20230708/ManageSystem/src/views/iot/Template.vue
<script>
export default {
  data() {
    return {
      // 相关类别的全部数据。
      iotThingsList: [],
      iotDataList: [],

      //筛选区域需要的状态。
      filter: {
        templateName: "",
        type: "",
      },

      //分页相关的状态。
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
    };
  },
  methods: {
    // 获取物模型全部类型。
    async queryIotThingsList() {
      let arr = await this.$API.iot.queryIotThingsType();
      this.iotThingsList = Object.freeze(arr);
      console.log(`arr-->`, arr);
    },
    // 获取全部的数据类别。
    async queryIotDataList() {
      let arr = await this.$API.iot.queryIotDataType();
      this.iotDataList = Object.freeze(arr);
    },
    //获取物模型列表数据。
    async initData() {
      //   console.log(`initData-->`);
      let {
        page: { pageNum, pageSize },
        filter: { templateName, type },
      } = this;
      try {
        let { code } = await this.$API.iot.queryTemplateList({
          pageNum,
          pageSize,
          templateName,
          type,
        });
      } catch (error) {
        console.log(`error:-->`, error);
      }
    },
  },
  async created() {
    //并行获取三种数据:物模型类别、数据类别、物模型列表。
    this.queryIotThingsList();
    this.queryIotDataList();
    this.initData();
  },
};
</script>
循环绑定
<script>
export default {
  data() {
    return {
      // 相关类别的全部数据。
      iotThingsList: [],

      //筛选区域需要的状态。
      filter: {
        templateName: "",
        type: "",
      },
    };
  },
  methods: {
    // 获取物模型全部类型。
    async queryIotThingsList() {
      let arr = await this.$API.iot.queryIotThingsType();
      this.iotThingsList = Object.freeze(arr);
      console.log(`arr-->`, arr);
    },
  },
  async created() {
    //并行获取三种数据:物模型类别、数据类别、物模型列表。
    this.queryIotThingsList();
  },
};
</script>

<template>
  <div class="template-box">
    <!-- 筛选/操作区域 -->
    <div class="filter-box">
      <div class="filter">
        <div class="form-item">
          <label>名称</label>
          <el-input
            placeholder="请输入物模型名称"
            v-model.trim="filter.templateName"
            @keydown.native.enter="initData"
          />
        </div>
        <div class="form-item">
          <label>类别</label>
          <el-select v-model="filter.type" @change="initData">
            <el-option value="" label="全部" />
            <el-option
              v-for="item in iotThingsList"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            />
          </el-select>
        </div>
      </div>
    </div>
  </div>
</template>

表格绑定

<script>
export default {
  data() {
    return {
      // 相关类别的全部数据。
      iotThingsList: [],
      iotDataList: [],

      //筛选区域需要的状态。
      filter: {
        templateName: "",
        type: "",
      },

      //分页相关的状态。
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },

      // 表格相关的状态。
      table: {
        data: [],
        loading: false,
      },
    };
  },
  methods: {
    // 获取物模型全部类型。
    async queryIotThingsList() {
      let arr = await this.$API.iot.queryIotThingsType();
      this.iotThingsList = Object.freeze(arr);
      console.log(`arr-->`, arr);
    },
    // 获取全部的数据类别。
    async queryIotDataList() {
      let arr = await this.$API.iot.queryIotDataType();
      this.iotDataList = Object.freeze(arr);
    },
    //获取物模型列表数据。
    async initData() {
      this.table.loading = true;
      //   console.log(`initData-->`);
      let {
        page: { pageNum, pageSize },
        filter: { templateName, type },
      } = this;
      try {
        let { code, rows, total } = await this.$API.iot.queryTemplateList({
          pageNum,
          pageSize,
          templateName,
          type,
        });
        if (+code !== 200) {
          rows = [];
          total = 0;
        }
        this.page.total = total;
        this.table.data = Object.freeze(rows);
      } catch (error) {
        console.log(`error:-->`, error);
      }

      this.table.loading = false;
    },
  },
  async created() {
    //并行获取三种数据:物模型类别、数据类别、物模型列表。
    this.queryIotThingsList();
    this.queryIotDataList();
    this.initData();
  },
};
</script>

<template>
  <div class="template-box">
    <!-- 筛选/操作区域 -->
    <div class="filter-box">
      <div class="filter">
        <div class="form-item">
          <label>名称</label>
          <el-input
            placeholder="请输入物模型名称"
            v-model.trim="filter.templateName"
            @keydown.native.enter="initData"
          />
        </div>
        <div class="form-item">
          <label>类别</label>
          <el-select v-model="filter.type" @change="initData">
            <el-option value="" label="全部" />
            <el-option
              v-for="item in iotThingsList"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            />
          </el-select>
        </div>
      </div>
      <div class="handler">
        <el-button type="primary" ghost icon="el-icon-plus">新增</el-button>
        <el-button type="danger" ghost icon="el-icon-minus">删除</el-button>
        <el-button type="success" ghost icon="el-icon-download">下载</el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-box">
      <el-table stripe :data="table.data" v-loading="table.loading">
      </el-table>
    </div>
  </div>
</template>

element-ui的el-table自适应

  1. 父元素从大到小,表格不会自动缩小。解决方式为给el-table加个绝对定位。
<template>
  <div class="template-box">

    <!-- 表格区域 -->
    <div class="table-box">
      <el-table stripe :data="[]">
        <el-table-column type="selection" align="center" min-width="4%" />
        <el-table-column
          label="名称"
          prop="templateName"
          align="center"
          min-width="8%"
        />
      </el-table>
    </div>

  </div>
</template>

<style lang="less" scoped>
.table-box {
  position: relative;

  .el-table {
    position: absolute;
    width: 100%;
  }

}

</style>
分页选项
格式化表格内容
  1. el-table-column可选的属性

formatter

插槽

  1. 在插槽中处理数据不方便,所以在拿到数据后就提前处理好。
  2. element-ui中处理数据的时候:
    • 一般使用formatter来用做纯数据转换的或用jsx语法来写的组件或标签的格式。
    • 一般使用插槽来处理数据转成组件或标签的格式。

选中项

弹出层

进阶参考

  1. el-table-column可选的属性
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值