一、后端Django代码
DRF 定义搜索列env:
class HostViewset(BaseView):
"""
主机 CURD
"""
queryset = Host.objects.all()
serializer_class = HostSerializer
permission_classes = [IsSuperUser]
search_fields = ['hostname', 'ip', 'env']
二、前端iveiw html代码
<FormItem label="环境:" prop="env">
<Row>
<Col span="6">
<Select v-model="createDbForm.env">
<Option value="prd">生产</Option>
<Option value="pre">准生产</Option>
<Option value="test">测试</Option>
</Select>
</Col>
</Row>
</FormItem>
<FormItem label="地址:" prop="host">
<Row>
<Col span="6">
<Select v-model="createDbForm.host" filterable v-if="createDbForm.env==='test'">
<Option v-for="host in hostList" value="host.ip">{{host.ip}}</Option>
</Select>
<Select v-model="createDbForm.host" filterable v-else-if="createDbForm.env==='pre'">
<Option v-for="host in hostList" value="host.ip">{{host.ip}}</Option>
</Select>
<Select v-model="createDbForm.host" filterable v-else>
<Option v-for="host in hostList" value="host.ip">{{host.ip}}</Option>
</Select>
</Col>
</Row>
</FormItem>
根据选择的业务环境,来动态的显示当前业务环境下的主机ip列表!
三、前端vue js代码
1. 首先我们要先引入api接口方法
import {GetHostList} from '@/api/dbms/hosts'
2. 在向后端发起ajax请求时的参数
data() {
return {
getParams: {
page: 1,
pagesize: 10,
search: ''
}
}
}
3. 定义method,获取主机列表
我们前面在django rest freamwork的host 视图函数中(第一步)的search_field列中定义了env列,这样就可以在url中可以用:
http://xxoo.com/api/dbms/hosts/?search=test 来进行条件搜索。
handleGetHostList(val) { this.getParams['search'] = val GetHostList(this.getParams) .then(res => { this.hostList = res.data.results this.total = res.data.count } ) },
上面的代码可以巧妙的通过方法传入值(值根据选择变化),然后修改search的值。但是怎么去动态传入值呢?下面watch方法登场:
watch: { "createDbForm.env"() { delay(() => { this.handleGetHostList(this.createDbForm.env); }, 100); }, },
1). 通过watch监听createDbForm对象的env值;
2). 把env值传给handleGetHostList方法;
3). 这里使用节流匿名函数去调用方法,节流函数如下:
const delay = (function () { let timer = 0 return function (callback, ms) { clearTimeout(timer) timer = setTimeout(callback, ms) } })();
下面是表单所用到的createDbForm对象:
updateDbForm: { id: '', env: '', name: '', host: '', port: '', user: '', password: '', remark: '', },