vue向后台请求数据的配置和方法

一、与后台连接端口的配置

新建一个vue项目之后,向后台请求端口连接,作如下配置:

项目目录下的config,打开 index.js 

 下面的红色标识处需要重新配置相关参数,

 如下:

target: 'http://localhost:9085/',   这里的端口号对应后台启动的端口号;

     proxyTable: {
        '/api/*': {
          target: 'http://localhost:9085/',
          ws: true,
          changeOrigin: true,
          pathRewrite: {
            '^/api': ''
          },
        },
      },

二、使用 fetch 请求后台接口,获取数据信息

1. 首先在vue项目utils 工具包下创建fetch.js 文件,内容如下:

import axios from 'axios';
import {
  Message
} from 'element-ui';

export default function defaultFetch() {}

export async function fetch(options) {

  try {
    let instance = await axios.create({
      timeout: 20000, // 超时
      headers: {
        // 'X-touchspring-Token': store.state.user.token,
        'Content-Type': 'application/x-www-form-urlencoded',
      },
    });
    let result = await instance(options);
    result = result.data;
    console.log(result);
    if (result.code === 1200 || result.code === 2000) {
      return result;
    } else {
      Message({
        message: result.message,
        type: 'error',
        showClose: true,
        duration: 2 * 1000,
      });
    }
  } catch (err) {
    console.log(err)
  }
}

2. 在src 下新建一个 api 文件夹,创建一个 js 文件,(名字自己随意)如:indoorMap.js

在里面可以编辑各种向后台请求接口的方法:增删查改等···

 

 实现方法indoorMap.js 需引入fetch ,qs,两个文件;     qs.stringify() 实现 json 数据的格式化为字符串

import { fetch } from "../utils/fetch";
import qs from 'qs';

/**
 * 查询所有室内地图信息
 */
export function findAllIndoorMap() {
	return fetch({
        /*url与后台映射地址匹配;  method 与映射的方法匹配-->包括 GetMapping PostMapping
         *    PutMapping  DeleteMapping 等注解方法
         */
		url: '/api/indoorMaps',
		method: 'get',
	});
}

/**
 * 根据mapId查询indoorMap
 */
export function findIndoorMapByMapId(mapId) {
	return fetch({
		url: `/api/indoorMaps/${mapId}`,
		method: 'get',
	});
}

/**
 * 根据id查询indoorMap
 */
export function findIndoorMapById(id) {
	return fetch({
		url: `/api/indoorMapsIds/${id}`,
		method: 'get',
	});
}

/**
 * 添加
 */
export function insertIndoorMap(indoorMap) {
	return fetch({
		url: '/api/indoorMaps',
		method: 'post',
		data: qs.stringify(indoorMap),
	});
}

/**
 * 更新
 */
export function updateIndoorMap(indoorMap) {
	return fetch({
		url: '/api/indoorMaps',
		method: 'put',
		data: qs.stringify(indoorMap),
	});
}

3. 界面中实现与后台数据库进行增删查改功能 

首先在 script 中引入 indoormap.js 文件中的需要的方法,import 引入

代码横线处为引用方式  const result = 

<script>

	import {insertIndoorMap,updateIndoorMap,findAllIndoorMap,findIndoorMapById,} from "../api/indoorMap";
	import { formatDate } from '../utils/dateConvert';

	

	/**
	 * 弹窗提交数据
	 */
	async function submitData() {

		delete this.form.data.createAt;
		delete this.form.data.updateAt;
-------------------------------------------------------------------------------------
		const result = (this.form.data.id) ? await updateIndoorMap(this.form.data) : await insertIndoorMap(this.form.data);
		const messages = (this.form.data.id) ? '更新成功' : '添加成功';

		if (result.code === 1200) {
			this.$message({
				message: messages,
				type: 'success',
			});
			this.initData();
			this.dialogVisible = false;
		} else {
			this.$message({
				message: '添加失败',
				type: 'fail',
			});
			this.dialogVisible = false;
		}

	}

	/**
	 * 编辑按钮
	 */
	function editIndoorMap() {
		if (this.isSelectCurrentRow === true) {
			this.dialogVisible = true;
			this.dialogTitle = "编辑楼层信息";
		} else {
			this.$message({
				message: '请选中记录!',
				type: 'error',
			});
		}
	}

	/**
	 * 添加操作
	 */
	function addIndoorMap() {
		this.dialogTitle = '添加楼层信息';
		this.dialogVisible = true;
	}

	/**
	 * 处理关闭弹窗
	 */
	function handleClose() {
		this.form.data = {};
		this.dialogVisible = false;
	}

	/**
	 * 初始化数据列表
	 * @returns {Promise.<void>}
	 */
	async function initData() {
-------------------------------------------------------------------------------------
		const result = await findAllIndoorMap();
		if (result.code === 1200) {
			this.tableData = [];
			result.data.indoorMaps.forEach((im) => {
				let createAt = formatDate1(im.createAt);
				let updateAt = formatDate1(im.updateAt);
				let indoorMap = im;
				indoorMap.createAt = createAt;
				indoorMap.updateAt = updateAt;
				this.tableData.push(indoorMap);
			});
		}
	}

	

	/**
	 * 选中某行数据
	 * @param row
	 * @returns {Promise.<void>}
	 */
	async function rowClick(row) {
		this.isSelectCurrentRow = true;
		let id = row.id;
		if (id !== null) {
-------------------------------------------------------------------------------------
			const result = await findIndoorMapById(id);
			if (result.code === 1200) {
				this.form.data = result.data.indoorMaps;

				console.log("-图片地址-" + result.data.indoorMaps.image);
			}
		}

	}


	
	function cancelButton() {
		this.form.data = {};
		this.dialogVisible = false;
	}


	export default {
		data() {
			return {
				tableDisable: true,
				hideButton: true,
				tableData: [],
				totalDataCount: 1,
				pageCount: 5,
				pageSize: 1,

				doType: '',
				dialogTitle: '',
				dialogVisible: false,

				labelPosition: 'left',

				form: {
					data: {
						id: '',
						mapId: '',
						image: '',
						width: '',
						height: '',
						createAt: '',
						updateAt: '',
					},
				},

				

			};
		},
		methods: {

			initData,
			rowClick,
			handleClose,
			submitData,
			handleImageSuccess,
			addIndoorMap,
			editIndoorMap,
			formatDate1,
			cancelButton,

			hideTable() {
				this.tableDisable = !this.tableDisable;
				this.hideButton = !this.hideButton;
			},

		},


		created() {

			this.initData();
		},

	};
</script>

三、后台接口

 controller 层   对应接口的编写和  Maping接口

    /**
     * 查询当前项目所有室内地图
     *
     * @return .
     */
    @GetMapping("indoorMap/{projectId}")
    public ResultData findAllIndoorMap(@PathVariable("projectId") String projectId) {
        List<IndoorMapDto> indoorMapList = indoorMapDao.findByProjectId(projectId);
        if (indoorMapList != null) {
            return ResultData.ok().putDataValue("indoorMaps", indoorMapList);
        } else {
            return ResultData.notFound();
        }

    }


    /**
     * 根据mapId查询indoorMap
     *
     * @return .
     */
    @GetMapping("{mapId}/indoorMaps")
    public ResultData findIndoorMapByMapId(@PathVariable("mapId") String mapId) {
        IndoorMap indoorMap = indoorMapDao.findByMapId(mapId);
        if (indoorMap != null) {
            return ResultData.ok().putDataValue("indoorMaps", indoorMap);
        } else {
            return ResultData.notFound();
        }

    }


    
    /**
     * 根据id查询indoorMap
     *
     * @return .
     */
    @GetMapping("indoorMaps/{id}")
    public ResultData findIndoorMapById(@PathVariable("id") String id) {
        IndoorMap indoorMap = indoorMapDao.findById(id);
        if (indoorMap != null) {
            return ResultData.ok().putDataValue("indoorMaps", indoorMap);
        } else {
            return ResultData.notFound();
        }

    }


    /**
     * 保存
     *
     * @return .
     */
    @PostMapping("indoorMaps")
    public ResultData saveIndoorMap(IndoorMap indoorMap) {
        if (indoorMap != null) {
            //判断mapId是否一样
            indoorMap.setId(IdWorker.nextId());
            indoorMap.setCreateAt(new Date());
            indoorMap.setUpdateAt(new Date());
            int res = indoorMapDao.insertIndoorMap(indoorMap);
            if (res == 1) {
                return ResultData.ok().putDataValue("indoorMaps", indoorMap);
            } else {
                return ResultData.serverError();
            }
        } else {
            return ResultData.notFound();
        }

    }


    /**
     * 更新修改
     *
     * @return .
     */
    @PutMapping("indoorMaps")
    public ResultData updateIndoorMap(IndoorMap indoorMap) {
        if (indoorMap != null) {
            indoorMap.setUpdateAt(new Date());
            int res = indoorMapDao.updateIndoorMap(indoorMap);
            if (res == 1) {
                return ResultData.ok().putDataValue("indoorMaps", indoorMap);
            } else {
                return ResultData.serverError();
            }
        } else {
            return ResultData.notFound();
        }

    }


 

  • 3
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值