import { clone, errorMsg, staticName } from "@/utils/tools" export default { computed: { isAdd() { return this.action === 'add' }, isView() { return this.action === 'view' }, isEdit() { return this.action === 'edit' }, readonly() { if (!this.action) return true return this.isView } }, data() { return { rowStyle: 'margin-bottom: 10px', action: null, editData: null, canSave: false, form: {}, beforeHooks: [], afterHooks: [], rules: {} } }, onReady() { this.$refs.editForm.setRules( this.rules ) }, onLoad({ action, json }) { this.action = action if (action !== 'add' && !json) { return uni.navigateBack() } else if (json) { this.editData = JSON.parse(json) } }, created() { this.resetForm() }, mounted() { this.init() }, methods: { init() { this.beforeHooks = [] this.afterHooks = [] this.setUp && this.setUp() this.resetForm() this.afterReset && this.afterReset() Promise.all(this.beforeHooks.map(f => f(this.action))).then(_ => { if (this.loadDataCondition()) { uni.showLoading({ title: '加载数据 ...' }) this.getData().then(resp => { const d = this.parseResp(resp) if (d) { this.form = d return Promise.all(this.afterHooks.map(f => f(this.action, resp, d))) } else { return Promise.reject('获取数据失败') } }).then(_ => { if (!this.readonly) { this.canSave = true } }).catch(err => { if (err) { errorMsg(err) } this.canSave = false }).finally(_ => { uni.hideLoading() }) } }).catch(err => { errorMsg('初始化失败') if (err) { console.error(err) } }) }, resetForm() { this.canSave = false this.form = {} if ('defaultForm' in this) { this.form = clone(this.defaultForm) } if ('tableData' in this) { this.tableData = [] } if ('uploadFiles' in this) { this.uploadFiles = [] } }, loadDataCondition() { return this.isView || this.isEdit }, addBeforeHook(hook) { this.beforeHooks.push(hook) }, addAfterHook(hook) { this.afterHooks.push(hook) }, afterReset() {}, getDataParam() { return this.editData.id }, parseResp(resp) { return resp.data }, getData() { return this.getDataFun()(this.getDataParam()) }, getDataFun() { return Promise.resolve({}) }, staticName, back(refresh = false) { console.log(this, this.listUrl, refresh); if (this.listUrl) { const url = `${this.listUrl}?refresh=${refresh}` uni.redirectTo({ url }) } else { uni.navigateBack() } }, getSaveFun() { }, getLocalData() { return { ...this.form } }, saveSuccessful(resp) { return resp.code === 200 }, beforeSaveCheck() { return Promise.resolve() }, save() { console.log(this.$refs.editForm.validate); this.beforeSaveCheck().then(_ => { this.$refs.editForm.validate().then(res => { this.getSaveFun()(this.getLocalData()).then(resp => { console.log('save callback', resp); if (this.saveSuccessful(resp)) { this.back(true) } else { errorMsg('操作失败') } }) }) }).catch(err => { if(err) { errorMsg(err) } }) } }, }