今天开发遇到一个新问题,需求是要求当服务器有新数据推送过来的时候页面有提示,分别是title标题滚动提示和弹窗提示。下面我就来说明一下这两种方式都是如何实现的。
1.首先是页面title标题滚动,首先定义好title要显示的内容,demo中我写了一条死数据
document.title='你有一条新的消息'
定义text=document.title
data() {
return {
text: null,
}
},
在methods里面添加newtext方法,通过字符串的substring方法截取title
newtext() {
document.title = this.text.substring(1, this.text.length) + this.text.substring(0, 1)
this.text = document.title.substring(0, this.text.length)
this.time()
},
再添加定时器调用newtext方法即可实现title轮播。
2.现成的UI库中大多数的消息提示都是在本页面提示,并不能够实现桌面级消息提示,但是在需求中需要能够有一个跨页面进行的一个消息提示,那该如何去做呢?
主要使用的是浏览器的Notification方法
created(){
if (window.Notification) {
// 浏览器通知--window.Notification
if (Notification.permission == "granted") {
console.log("允许通知")
}else if( Notification.permission != "denied"){
console.log("需要通知权限")
Notification.requestPermission((permission)=> {});
}
} else {
console.error('浏览器不支持Notification');
}
},
在created里面对浏览器做一个Notification方法校验和权限授权,如果浏览器支持Notification方法的话会弹出权限框,点击允许给Notification进行授权
在methods中定义消息的弹出类型和内容
methods: {
popNotice(user, content) {
let that = this;
if (Notification.permission == "granted") {
let notification = new Notification(user, {
body: content,
});
notification.onclick = function(e) {
that.$nextTick(() => {
setTimeout(()=>{
//具体操作
},500);
});
//可直接打开通知notification相关联的tab窗
window.focus();
notification.close();
};
}
},
handle(){
this.popNotice('您有一条新的消息')
}
}
接着,消息就会以浏览器通知的形式弹出