Uniapp中怎么实现全局消息提示及其组件?下面本篇文章给大家介绍一下Uniapp全局消息提示及其组件的实现方法,希望对大家有所帮助!
Uniapp中怎么实现全局消息提示及其组件?下面本篇文章给大家介绍一下Uniapp全局消息提示及其组件的实现方法,希望对大家有所帮助!
实现1.短轮询请求-App.vue中async created(){const _this=thissetInterval(async ()=>{ const res=await _this.$ajax({ url:`/api/notice/status` }) if(res.data.code===200){ const value=res.data.data.hasNew _this.$store.commit({type: 'changeNew', value}) } },6000) } 2.全局消息提示组件消息请求后需要有一个全局的自定义组件来展示消息,但是遇到一个问题,那就是在Unipp中,
虽然 (1)定义一个GlobalMessage.vue组件自定义一个消息提示组件,text将会是我们传入的提示消息参数 <template> <div class='message-container'> 全局消息提示 {{text}} </div> </template> <script></script> <style lang="scss" scoped> .message-container{ position: fixed; top: 10%; z-index: 2000; left: 10%; width: 200px; height: 200px; background-color: red; } </style> (2)新建GlobalMessage.js将自定义组件引入, { template:'', data(){ return { 属性 } } } 但此时创建的并非组件实例,需要通过new 方式创建组件实例,参数包括创建的组件Dom节点,组件内部属性。然后使用 function showMessage(text,duration){ const MessageDom=new MessageConstructor({ el:document.createElement('div'),data(){ return {text:text, } } })document.body.appendChild(MessageDom.$el) } 接下来我们需要将该方法挂载到vue原型上,从而能够像 function registryMessage(){ vue.prototype.$message=showMessage } export default registryMessage GlobalMessage.js全部代码 import vue from "vue" import GlobalMessage from './GlobalMessage.vue'; const MessageConstructor= vue.extend(GlobalMessage) function showMessage(text,duration){ const MessageDom=new MessageConstructor({ el:document.createElement('div'),data(){ return {text:text, } } }) document.body.appendChild(MessageDom.$el) } function registryMessage(){ vue.prototype.$message=showMessage } export default registryMessage (3)main.js中将我们抛出的方法引入,使用 import GlobalMessage from "./GlobalMessage.js"; // 这里也可以直接执行 toastRegistry()Vue.use(GlobalMessage); 使用 this.$message('测试数据') 3.小程序中如何实现超导马得,刚刚能够全局使用
uni-app的js API 那么需求不能不完成,我们采用另外一套方案,使用vuex状态机来进行全局状态控制,将自定义组件放在需要的页面中,使用状态机来控制消息的提示内容以及展示与隐藏。注:请自行安装配置vuex。
import GlobalMessage from '@/components/common/GlobalMessage.vue'; Vue.component('GlobalMessage',GlobalMessage) 在需要的页面放置 4.vue-inset-loader的使用
vue-inset-loader (1)安装
(2)vue.config.js注入loader没有 module: { rules: [ { test: /.vue$/, use:{ loader: "vue-inset-loader" // // 针对Hbuilder工具创建的uni-app项目 // loader: path.resolve(__dirname,"./node_modules/vue-inset-loader") } } ] }, // 支持自定义pages.json文件路径 // options: { // pagesPath: path.resolve(__dirname,'./src/pages.json') // } (3)pages.json配置文件中添加insetLoader"insetLoader": { "config":{ "message": "<GlobalMessage></GlobalMessage>", }, // 全局配置 "label":["confirm"], "rootEle":"div" }, "pages": [ { "path": "pages/tabbar/index/index", "style": { "navigationBarTitleText": "测试页面", // 单独配置,用法跟全局配置一致,优先级高于全局 "label": ["confirm","abc"], "rootEle":"div" } }, ]
? 总结
推荐:《uniapp教程》 以上就是聊聊使用Uniapp怎么实现全局消息提示及其组件的详细内容,更多请关注模板之家(www.mb5.com.cn)其它相关文章! |