cd /projectFloder
yarn serve

前言

1、axios配置、封装。

2、加载使用element-ui

3、增删改查示例

一、axios自定义

代码如下(vue.config.js): 

const proxyObj = {}
proxyObj['/'] = {
  target: 'http://localhost:1011',
  changeOrigin: true,
  pathRewrite: {
    '^/': ''
  }
}
//解决AMap报错:AMap undefined报错
module.exports = {
  devServer: {
    host: 'localhost',
    port: 8080,
    proxy: proxyObj
  },
}

代码如下(main.js): 

import VueAxios from 'vue-axios'
import axios from 'axios'
Vue.prototype.$axios = axios
axios.defaults.baseURL = '/device'
Vue.use(VueAxios, axios);

 封装方法:新建 utils文件夹,里面新建 api.js和http.js文件

代码如下(api.js): 


//引用上面的http.js文件
import { get, post } from "@/utils/http.js";

// Api for deveList
export const getdeviceListTable = formData => get("/list", formData);
export const selectDeviceLikeId = ids => post(`/selectDeviceLikeId/${ids}`);
export const seleDeviceById = ids => post(`/selectDeviceById/${ids}`);
export const deleDeviceById = formData => get(`/deleById/${formData}`);
export const submitDevice = formData => post("/subDevice", formData);


//Api for taskList

代码如下(http.js): 


//http.js文件
import axios from "axios";
axios.defaults.timeout = 5000; //超时时间设置
axios.defaults.withCredentials = true; //true允许跨域
//Content-Type 响应头
axios.defaults.headers.post["Content-Type"] =
    "application/x-www-form-urlencoded;charset=UTF-8";
let token = localStorage.getItem('authorization');
axios.defaults.headers.post["authorization"] = token;
// if (process.env.NODE_ENV === "production") {
//     /*第二层if,根据.env文件中的VUE_APP_FLAG判断是生产环境还是测试环境*/
//     if (process.env.VUE_APP_FLAG === "pro") {
//         //production 生产环境
//         axios.defaults.baseURL = "http://localhost:1011";
//     } else {
//         //test 测试环境
//         axios.defaults.baseURL = "";
//     }
// } else {
//     //dev 开发环境
//     axios.defaults.baseURL = "http://localhost:1011";
// }
//axios.defaults.baseURL = "http://localhost:1011";


/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function get(url, params = {}) {
    return new Promise((resolve, reject) => {
        axios
            .get(url, {
                params: params
            })
            .then(response => {
                resolve(response.data);
            })
            .catch(err => {
                reject(err);
            });
    });
}

/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post(url, data = {}) {
    return new Promise((resolve, reject) => {
        axios.post(url, data).then(
            response => {
                resolve(response.data);
            },
            err => {
                reject(err);
            }
        );
    });
}

/**
 * 封装delete请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function deletes(url, data = {}) {
    return new Promise((resolve, reject) => {
        axios.delete(url, data).then(
            response => {
                resolve(response.data);
            },
            err => {
                reject(err);
            }
        );
    });
}

/**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put(url, data = {}) {
    return new Promise((resolve, reject) => {
        axios.put(url, data).then(
            response => {
                resolve(response.data);
            },
            err => {
                reject(err);
            }
        );
    });
}

二、vue使用element-ui

1.引入库

代码如下(示例):

yarn add element-ui

2.main.js配置

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

Vue.use(ElementUI);

三、增删改查

代码如下(示例):

<template>
  <el-card :span="24">
    <el-row>
      <el-col :span="2">
        <el-button type="primary" @click="editDialogVisible = true"
          >新增</el-button
        >
      </el-col>
      <el-col :span="6">
        <el-input placeholder="请输入序列号" v-model="id" clearable>
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="selectDeviceLikeId(id)"
          ></el-button>
        </el-input>
      </el-col>
    </el-row>
    <el-row>
      <el-table :data="tableData">
        <el-table-column
          label="序号"
          prop="id"
          type="index"
          sortable="custom"
          align="center"
        ></el-table-column>

        <el-table-column
          label="厂家"
          width="130px"
          align="center"
          prop="manufactor"
        >
        </el-table-column>
        <el-table-column
          label="地址IP"
          width="130px"
          align="center"
          prop="ipAdress"
        >
        </el-table-column>
        <el-table-column
          label="端口"
          width="130px"
          align="center"
          prop="dvPort"
        >
        </el-table-column>
        <el-table-column label="SN码" width="400px" align="center" prop="sn">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row.id)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <!--model:增加弹窗-->
    <el-dialog title="增加设备" :visible.sync="editDialogVisible" width="30%">
      <el-form label-width="80px" :model="deviceAddDate">
        <el-form-item label="SN码">
          <el-input v-model="deviceAddDate.sn"></el-input>
        </el-form-item>
        <el-form-item label="地址IP">
          <el-input v-model="deviceAddDate.ipAdress"></el-input>
        </el-form-item>
        <el-form-item label="端口">
          <el-input v-model="deviceAddDate.dvPort"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSubmitDevice(deviceAddDate)"
          >提 交</el-button
        >
      </span>
    </el-dialog>
    <!--修改弹窗-->
    <el-dialog
      center
      title="修改"
      :visible.sync="updateDialogVisible"
      width="30%"
    >
      <el-form :model="deviceDate" ref="deviceDate" label-width="90px">
        <el-form-item label="厂家" prop="manufactor">
          <el-input v-model="deviceDate.manufactor"></el-input>
        </el-form-item>
        <el-form-item label="IP地址" prop="ipAdress">
          <el-input v-model="deviceDate.ipAdress"></el-input>
        </el-form-item>
        <el-form-item label="端口" prop="dvPort">
          <el-input v-model="deviceDate.dvPort"></el-input>
        </el-form-item>
        <el-form-item label="序列号" prop="sn">
          <el-input v-model="deviceDate.sn"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="insertSubmit(deviceDate)"
          >修 改</el-button
        >
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import {
  getdeviceListTable,
  submitDevice,
  deleDeviceById,
  seleDeviceById,
  selectDeviceLikeId
} from "@/utils/api.js"; // 调用api 登录接口

export default {
  data() {
    return {
      tableData: [],
      diviceForm: [],
      search: "",
      id: "",
      editDialogVisible: false,
      updateDialogVisible: false,
      deviceAddDate: {
        addTime: "",
        dvPort: "",
        id: "",
        ipAdress: "",
        manufactor: "",
        passWord: "",
        phyAdress: "",
        phyRelease: "",
        sn: "",
        statues: "",
        userName: "",
      },
      deviceDate: {
        addTime: "",
        dvPort: "",
        id: "",
        ipAdress: "",
        manufactor: "",
        passWord: "",
        phyAdress: "",
        phyRelease: "",
        sn: "",
        statues: "",
        userName: "",
      },
    };
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      getdeviceListTable()
        .then((res) => {
          this.tableData = res;
          this.total = res.length;
          console.log(JSON.stringify(res.data));
        })
        .catch((err) => {
          console.log("err==>", err);
        });
    },
    addSubmitDevice(deviceAddDate) {
      var that = this;
      submitDevice(deviceAddDate)
        .then((res) => {
          that.editDialogVisible = false;
          this.init();
          this.deviceAddDate = {};
          console.log(JSON.stringify(res));
        })
        .catch((err) => {
          console.log("err==>", err);
        });
    },
    handleEdit(index, id) {
      seleDeviceById(id)
        .then((res) => {
          this.deviceDate = res;
          console.log(JSON.stringify(res));
        })
        .catch((err) => {
          console.log("err==>", err);
        });

      this.updateDialogVisible = true;
    },
    handleDelete(index) {
      deleDeviceById(index)
        .then((res) => {
          this.init();
          console.log(JSON.stringify(res));
        })
        .catch((err) => {
          console.log("err==>", err);
        });
    },

    insertSubmit(deviceDate) {
      submitDevice(deviceDate)
        .then((res) => {
          this.updateDialogVisible = false;
          this.init();
          console.log(JSON.stringify(res));
        })
        .catch((err) => {
          console.log("err==>", err);
        });
    },
    selectDeviceLikeId(id) {
      selectDeviceLikeId(id)
        .then((res) => {
        this.tableData = res;
          this.total = res.length;
          console.log(JSON.stringify(res));
        })
        .catch((err) => {
          console.log("err==>", err);
        });
    },
  },
};
</script>

总结

vue页面有三部分,数据、展示、交互,我们可以用UI来做展示,数据在开始的时候进行个定义,定义之后交互得到数据进行赋值,vue特性可以随数据的改变改变模型。

Logo

前往低代码交流专区

更多推荐