Vue代码优化之mixins 混合器的使用
程序员文章站
2022-06-25 08:22:06
使用场景 主要抽离组件共用的代码,如各个页面中分页组件的data、methods,和ui原型中统一的confirm和alert弹窗 以及加载的进度条等 混合器: // mixin.js export const page = { data() { return { pageSize:20, curr ......
使用场景
主要抽离组件共用的代码,如各个页面中分页组件的data、methods,和ui原型中统一的confirm和alert弹窗
以及加载的进度条等
混合器:
// mixin.js export const page = { data() { return { pagesize:20, currentpage: 1 pagelength: 10, } }, methods: { /** * 上一页 */ prevpage (page) { ... }, /** * 下一页 */ nextpage (page) { ... } /** * 跳转到当前页 */ currentpage (page) { ... } } } export const ui= { methods: { async loadingdata (target, callback) { const loading = this.$loading({ lock: true, text: '处理中...', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.5)', target: target ? target : document.body, }); try { await callback(); } finally { loading.close(); } }, confirm (msg,title='提示',doconfirm, docancel, options={}) { let defaultopts ={ type: 'warning' }; let opts = { ...defaultopts, ...options }; let iconclassobj = { 'warning':'el-icon-warning-outline', 'err':'el-icon-circle-close', 'success':'el-icon-circle-check' } let iconcolorobj = { 'warning':'#e6a23c', 'err':'#ee020b', 'success':'#14b216' } const iconclass = iconclassobj[opts.type]; const iconcolor = iconcolorobj[opts.type]; let html =`<i style="color:${iconcolor}; font-size:66px;margin-top: -22px;" class="${iconclass}"></i><br> <p style="font-size:16px;color: #333333;font-weight:500;margin-top: 7px;">${title}</p><span style="font-size:14px;color: #969696;font-weight:400;">${msg}</span>`; this.$confirm(html, '', { confirmbuttontext: '确定', cancelbuttontext: '取消', dangerouslyusehtmlstring: true, center: true, cancelbuttonclass:'dialog-cancel-btn', confirmbuttonclass: 'dialog-confirm-btn' }).then(async () => { try { if (doconfirm) { await doconfirm(); } } catch (err) { console.log(err); } }).catch(async () => { try { if (docancel) { await docancel(); } } catch (err) { console.log(err); } }); }, alert (msg, title='提示', docancel) { this.$alert(msg, title, { showconfirmbutton: false, callback: async action => { if (action == 'cancel') { if (docancel) { await docancel(); } } }, }); }, }, };
页面.vue
<template> <div class="home-model"> <my-table :data="data"></my-table> <my-paging :page-length="pagelength" :page-size="pagesize" :current-page="currentpage" :total="total"> </my-paging> </div> </template> <script> import page from '../mixins/mixin' export default { mixins: [page], data () { return { data: [], pagelength: 10, pagesize: 1, currentpage: 1, total: 20 } }, methods:{ handledelete(){ this.confirm('请确认是否需要删除?','确认删除?',async () => { await this.loadingdata('.el-container', async () => { await this.apideletdata(); }); this.loadlistdata(); }); } } } </script>
可以拆成三部分写:ui部分、分页数据部分、
userdata的部分
后续补vuex的内容
下一篇: java 文件上传