最近新学Vue,后台开发中经常用到提交,索性把提交功能给做成全局方法,下面为封装的代码。
//封装默认提交方法 Vue.prototype.mySubmit = function (options) { var that = this; //避免this指向被改变 var url = options.url || location.href; var post = options.post || "post"; var data = options.data || {}; //要提交的数据 var callBack = options.callBack; var successMsg = options.successMsg || "恭喜你,提交成功!"; var confirmMsg = options.confirmMsg; //确定文字,如果有会先弹出是否确定按钮 varformName = options.formName; this.$refs["formName"].validate(function (valid) { if (valid) { if (confirmMsg) { that.$confirm(confirmMsg, '提示', { confirmButtonText: '确定', cancelButtonText: '取消', }).then(() => { submit(that); }).catch(() => { }); } else { submit(that); } } else { return false; } }); function submit(vue) { var loading = ELEMENT.Loading.service({ fullscreen: true }); var ajaxOptions = { url: url, type: "post", data: data, success: function (data) { ELEMENT.Message.success({ message: successMsg, }); loading.close(); if (typeof callBack == "function") { callBack(); } }, fail: function (data) { alert(data); loading.close(); } } Ajax(ajaxOptions); } }
使用方法如下:
html部分:
<button type="button" v-on:click="submit" class="btn btn-primary">提交</button>
js部分
var vue= new Vue({ el: "#el", data: { formData: {}, }, methods: { submit: function () { this.paSubmit({url:"/post/",data:this.formData}); }, }, });