需求:每個界面中都有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 導入的這個子組件;