书接上回,上个帖子写的主题切换,这个该写全局组件了,也是项目写着写着发现功能竟然有全局的,又是因为没有根组件[擦汗],ps:下次如果用uniapp,必须要做全产品功能,然后想好到底怎么搭这个框架!!!
好了,接下来就是说下这帖子我的需求。项目有个消息提醒功能,类似就是一个悬浮按钮,全局显示,一来消息,上面的数字就会变化,功能很简单,但是在uniapp实现起来却有点麻烦。
网上有很多老铁给的方法很通用啊,就是写个公共组件,然后每个组件都引用一遍,这里我想大喊一声,卧槽(我屮艸芔茻),如果我想这么麻烦那干嘛还来查?
然后就是发现了uniapp支持原生plus,发现通过plus.nativeObj.View可以实现项目要求的功能。在项目中引入vuex,这样就可以哪里想显示就哪里让它显示。好了,上代码:
vuex:
const state = {
view: null,
alert: null
}
const mutations = {
close(state) {
state.view.close()
state.view = null
},
// 显示按钮
show(state) {
if (!state.view) {
create(state)
return
}
state.view.show();
if (!state.alert) {
create(state)
return
}
state.alert.show();
},
// 隐藏按钮
hide(state) {
state.view && state.view.hide()
state.alert && state.alert.hide()
}
}
function create(state){
uni.getSystemInfo({
success:(info)=>{
//初始化存一些设备相关的参数
console.log(info.screenHeight)
try {
uni.setStorageSync('screenHeight', info.screenHeight);
uni.setStorageSync('screenWidth', info.screenWidth);
} catch (e) {
// error
}
}
})
// #ifdef APP-PLUS
state.view = new plus.nativeObj.View('bottom-btn', {
left: (uni.getStorageSync('screenWidth') - 50)+'px',
bottom: '20px',
height: '45px',
width: '100px',
backgroundColor: 'rgba(239,239,239,0)'
},
[{
tag: 'rect',
id: 'rect',
rectStyles: {color:'rgba(239,239,239,0.5)', radius: '27px'},
position:{top: '0px', left: '0px', width: '100%', height: '100%'}
}]
);
state.alert = new plus.nativeObj.View('bottom-btn', {
left: (uni.getStorageSync('screenWidth') - 50)+'px',
bottom: '20px',
height: '45px',
width: '100px',
backgroundColor: 'rgba(0,0,0,0)'
},
[{
tag: 'img',
id: 'img',
src: './static/home/messageIcon.png',
position:{top: '7px', left: '10px', width: '30px', height: '30px'}
},{
tag: 'rect',
id: 'rect',
rectStyles: {color:'rgba(221,82,77,1)', radius: '7px'},
position:{top: '4px', left: '28px', width: '20px', height: '14px'}
}]
);
let richtext = '<font color="#fff" style="font-size:10px;">55</font>';
// 绘制文本
state.alert.drawRichText(richtext, {top:'4px',left:'31px',width:'13px',height:'20px'},{align:'center'});
state.alert.setTouchEventRect({top:'7px',left:'10px',width:'30px',height:'30px'});
// 监听点击事件
state.alert.addEventListener("click", (e) => {
console.log(e)
uni.navigateTo({
url: '/pages/message/message'
})
}, false);
// #endif
}
const actions = {
}
const getters = {
}
export default {
namespaced: true,
state,
mutations,
actions,
getters
}
然后混入到vue中,如果不知道咋整的童鞋可以去看上一篇文章,再就是使用了,上代码:
App.vue
onShow: function () {
this.show();
}
这就全局显示了,如果想隐藏的哪个页面就用调用隐藏方法吧~
2022-01-19
已经将此组件封装上传至uniapp,可以直接下载使用,欢迎大家下载,发个组件链接:
https://ext.dcloud.net.cn/plugin?id=7280
全文完~