vuejs使用Element-ui封装dialog公用数据列表弹出插件
vuejs使用Element-ui封装dialog公用数据列表弹出插件
dialog代码
<template> <el-dialog :title="modalObj.title" :visible.sync="modalShow" width="60%" center :before-close="modalClose"> <div style="display: flex;align-items: center;justify-content: center;flex-direction:column"> <div style="width: 80%;"> <el-input style="width: 80%" size="small" v-model="inputVal"></el-input> <el-button type="primary" size="small" @click="getData">搜索</el-button> </div> <br> <div style="width: 90%"> <el-table border highlight-current-row :data="dataList.list" :height="tableHeight"> <el-table-column v-for="(item,key) in modalObj.tableColumn" :prop="key" :label="item[0]" :width="item[1]" :key="key"></el-table-column> </el-table> </div> <div style="width: 80%;display: flex;flex-direction: column;align-items: center;justify-content: center;"> <el-pagination layout="prev, pager, next" :total="dataList.pages"></el-pagination> </div> </div> </el-dialog> </template> <script> import Global from @/js/Global.js; export default { name: "Modal", props: { modalObj : Object, modalShow : Boolean }, data(){ return { inputVal:, dataList : {}, queryParam : {currentPage:1,pageSize:20} } }, methods:{ modalClose(){ this.modalShow = false; }, getData(){ let that = this; that.queryParam[that.modalObj.condition] = that.inputVal; that.$http.post(Global.baseUrl+that.modalObj.url,that.queryParam).then(function (resp) { that.dataList = resp.data; }).catch(function (e){ console.log(e); }); } }, computed:{ tableHeight(){ return document.body.clientHeight - 200; } }, //这个地方需要监听modalShow的变化,如果modalShow发生变化后,触发父组件对modal-show的更新 watch:{ modalShow : function (val) { this.$emit(update:modalShow, val); } } } </script> <style scoped> </style>
父控件调用方法
//下边的注释摘抄自vuejs官网:https://cn.vuejs.org/v2/guide/components.html#sync-修饰符 //在这种情况下,需要对一个 prop 进行“双向绑定”,这正是 Vue 1.x 中的 .sync 修饰符所提供的功能 //但也会导致问题,因为它破坏了单向数据流。由于子组件改变 prop 的代码和普通的状态改动代码毫无区别,当光看子组件的代码时,你完全不知道它何时悄悄地改变了父组件的状态 //上面所说的正是我们在 2.0 中移除 .sync 的理由。但是在 2.0 发布之后的实际应用中,我们发现 .sync 还是有其适用之处,比如在开发可复用的组件库时。我们需要做的只是让子组件改变父组件状态的代码更容易被区分。 //从 2.3.0 起我们重新引入了 .sync 修饰符,但是这次它只是作为一个编译时的语法糖存在。它会被扩展为一个自动更新父组件属性的 v-on 监听器。 <modal :modal-obj=modalObj :modal-show.sync="modalVisible"></modal> ...... export default { data() { return { modalVisible : false, ...... } } }
总结
刚开始没有使用sync时,遇到问题如下:设置.visible.sync为prop中的属性,结果直接修改prop后,dialog并没有直接隐藏。所以主要还是.sync 的使用让dialog的显示和隐藏更简单快捷