消息提示
页面很多地方会用到消息提醒的功能,如保存成功、失败、删除等。
这里使用mu-snackbar
组件,并使用vuex
做全局的管理。
在vuex
中增加sys.js
文件,增加一个message
状态:
const state = {
message: {}
};
然后增加actions
如下:
setMessage({ commit }, { type, message }) {
commit("SET_MESSAGE", {
type, // 消息类型
message, // 消息内容
date: Date.now()
});
}
在组件中增加Message.vue
文件,主要通过监听message
来触发消息提醒。
部分代码如下:
methods: {
showMsg(type, msg) {
if (this.color.timer) clearTimeout(this.color.timer);
this.color.color = type;
this.color.message = msg;
this.color.open = true;
this.color.timer = setTimeout(() => {
this.color.open = false;
}, this.color.timeout);
}
},
watch: {
message: {
handler: function(v) {
this.showMsg(v.type, v.message);
},
deep: true
}
}
然后将此组件引入到主文件App.vue
中即可。
调用的时候就可以通过vuex
的setMessage
来触发。
确认对话框
确认组件也是比较常用的,如删除前确认等,我们也可以将其封装成单独的组件来调用。
muse-ui
中提供了mu-dialog
对话框,我们可以直接在此组件的的基础上进行封装。
<template>
<mu-dialog :title="title" width="400" max-width="80%" :esc-press-close="true" :overlay-close="false" :open.sync="openAlert">
{{content}}
<mu-button slot="actions" flat @click="clickBtn(false)">{{btnCancel}}</mu-button>
<mu-button slot="actions" flat color="primary" @click="clickBtn(true)">{{btnConfirm}}</mu-button>
</mu-dialog>
</template>
<script>
export default {
data() {
return {
title: "",
content: "",
btnCancel: "取消",
btnConfirm: "确认",
openAlert: false,
flag: false,
callback: function() {}
};
},
methods: {
show(opt, cb) {
this.title = opt.title || "消息确认";
this.content = opt.content;
opt.cancelBtnText ? (this.btnCancel = opt.cancelBtnText) : "";
opt.confirmBtnText ? (this.btnConfirm = opt.confirmBtnText) : "";
cb ? (this.callback = cb) : "";
this.openAlert = true;
},
clickBtn(flag) {
this.flag = flag;
this.openAlert = false;
this.callback(flag);
}
}
};
</script>
调用的时候就可以直接通过调用show
方法来使用,并传回回调,来确认是点击了确定还是取消。
加载loading
加载动画是比较简单的,使用mu-circular-progress
,直接通过vuex
来控制,通过一个状态,在每个请求之前和之后调用显示和隐藏就可以了。
在组件中增加Loading.vue
并引入到App.vue
中。
组件代码如下:
<template>
<div class="loading" v-show="loading">
<mu-circular-progress class="circ" :size="48"></mu-circular-progress>
</div>
</template>
<script>
import { mapState } from "vuex";
export default {
computed: {
...mapState({
loading: ({ sys }) => sys.loading
})
}
};
</script>
<style lang="scss" scoped>
.loading {
background-color: rgba(0, 0, 0, 0.2);
position: absolute;
z-index: 2000;
left: 0;
right: 0;
top: 0;
bottom: 0;
.circ {
left: 50%;
top: 40%;
}
}
</style>
这样通过改变loading
为true
或false
就可以显示和隐藏加载动画。
保存文章的调用例子
async createPost({ dispatch }, post) {
dispatch("setLoading", true); // 显示loading
let { data } = await Axios.post("blog/post", post);
let id = "";
if (!data.errmsg) {
dispatch("setMessage", { type: "success", message: "保存成功" }); // 显示保存成功消息提醒
id = data.data;
} else {
// 显示保存失败消息提醒
dispatch("setMessage", {
type: "error",
message: data.errmsg || "保存失败"
});
}
dispatch("setLoading", false); // 隐藏loading
return id;
},
博客地址: alibt.top
更多精彩,请关注我的公众号!