需求:每个界面中都有API接口调用文档的查看按钮,点击可以查看不同接口的接口文档!
分析:
1、用vue写一个子组件 component,其中API文档中的各种入参、调用示例、返回参数以及返回示例等可以作为子组件的props参数;
2、然后一点需要注意的是:当子组件点击关闭查看界面的时候,如何将关闭的状态值向上传递给父组件($emit);
代码示例:
1、子组件部分(子组件的名称叫 ApiWord.vue):
<template>
<el-dialog :title="title" :visible="dialogTableVisible" @close="closed">
<p>
<strong>简要描述:</strong>
</p>
<ul>
<li>根据上传的图片,识别出图片中的内容</li>
</ul>
<p>
<strong>请求URL:</strong>
</p>
<ul>
<li><code>{{requestUrl}}</code></li>
</ul>
<p><strong>请求方式:</strong></p>
<ul>
<li>POST</li>
</ul>
<p><strong>请求参数:</strong></p>
<el-table :data="gridParamData">
<el-table-column property="paramName" label="参数名" width="150"></el-table-column>
<el-table-column property="paramType" label="类型" width="200"></el-table-column>
<el-table-column property="required" label="必选"></el-table-column>
<el-table-column property="desc" label="说明"></el-table-column>
</el-table>
<p><strong>返回参数:</strong></p>
<el-table :data="gridResultData">
<el-table-column property="paramName" label="参数名" width="150"></el-table-column>
<el-table-column property="paramType" label="类型" width="200"></el-table-column>
<el-table-column property="desc" label="说明"></el-table-column>
</el-table>
<p><strong>返回示例</strong></p>
<pre>{{parse(resultExample)}}</pre>
</el-dialog>
</template>
<script>
export default {
name: "ApiWord",
props: {
title: {type: String, default: "票据混贴接口调用文档"},
requestUrl: {type: String, default: "http://xx.com/services/ocr"},
dialogTableVisible: {type: Boolean, default: false},
gridParamData: {type: Array, default: [{
paramName: 'image',
paramType: 'string',
required: '是',
desc: '图像base64编码后的字符串,图像需是 JPG、PNG、BMP 其中之一的格式'
}]},
gridResultData: {type: Array, default: [{
paramName: 'errorcode',
paramType: 'int',
desc: '返回码;0表示成功,非0表示出错'
}]},
resultExample: {type: String}
},
methods:{
parse(str) {
return JSON.stringify(JSON.parse(str), null, "\t");
},
closed(){
// this.dialogTableVisible = false; //不能有这一行代码,不然会报错:不能在子组件内部修改props中的值
// this.$emit('toggle', this.dialogTableVisible);
this.$emit('toggle', false); //子组件可以使用 $emit 触发父组件的自定义事件(既使用该子组件中的toggle方法)。
}
}
}
</script>
<style>
.el-dialog__title{
font-size: 25px;
}
.el-dialog{
width: 60% !important;
}
.el-dialog__body{
text-align: left !important;
}
.el-table th{
background: aliceblue !important;
}
pre{
padding-left: 5px;
background-color: rgb(252, 252, 252);
border: 1px solid rgb(225, 225, 232);
}
</style>
2、父组件调用示例:
<template>
<div>
<el-button type="primary" @click="dialogTableVisible = true" style="width:155px; height:48px;">查看详情>></el-button>
<api-word :title=title
:requestUrl=requestUrl
:dialogTableVisible=dialogTableVisible
:gridParamData=gridParamData
:gridResultData=gridResultData
:resultExample=resultExample
@toggle="toggle">
</api-word>
</div>
</template>
<script>
import ApiWord from "../components/ApiWord";
export default {
components: {
ApiWord
}
}
</script>
注:父组件中需要 import 导入这个子组件;并且在 components 对象中添加上 import 导入的这个子组件;