How to implement global message prompts and components in Uniapp? The following article will introduce to you how to implement the Uniapp global message prompt and its components. I hope it will be helpful to you!
#Recently, there are project requirements. We can refresh messages globally in real time in H5 and mini programs, and make a message prompt globally. The prompt component also needs to customize the style. , First of all, there are two types of real-time message refreshes, one is short polling and the other is long polling.
The so-called short polling actually means that the front-end uses a timer to initiate requests to the back-end within a certain interval, and the back-end needs to optimize the polling request.
Long polling means that after sending the message request to the backend, the request is suspended, waiting for new messages to be returned from the backend, and then reinitiating the message request. In fact, it is a websocket communication. In view of the project launch time and cost, finally Select the short polling method, and the global message prompt is performed in 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) }
After the message request, a global custom component is needed to display the message, but we encountered a problem, that is, in Unipp,
Although App.vue
is the main component of uni-app, all pages are switched under App.vue
, which is the page entry file. But App.vue
itself is not a page, and view elements cannot be written here. The functions of this file include: calling application life cycle functions, configuring global styles, and configuring global storage globalData. That is to say, App.vue
can only write js and css, but cannot mount view elements. So, can I use components in js like this.$message
? , I thought of the way to use vue.prototype.$message
in Vue
to mount global components.
Customize a message prompt component, text will be the prompt message parameter we passed in
<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>
Introduce the custom component, vue.extend
You can use the basic Vue constructor to create a child Class, parameter is an object containing components. The object example is as follows:
{ template:'', data(){ return { 属性 } } }
But what is created at this time is not a component instance. You need to create a component instance through the new method. The parameters include the created component Dom node and the internal properties of the component. Then use document.body.appendChild
to render the component into the body. At this time, we can already call this method to mount the custom component globally.
function showMessage(text,duration){ const MessageDom=new MessageConstructor({ el:document.createElement('div'),data(){ return {text:text, } } })document.body.appendChild(MessageDom.$el) }
Next we need to mount this method to the vue prototype so that it can be used like this.$message
. We mount it on vue.prototype
Load $message
and export this method.
function registryMessage(){ vue.prototype.$message=showMessage } export default registryMessage
GlobalMessage.js all code
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
method that throws us in main.js Introduction, use Vue.use
for global registration, so that you can happily use this.$message
.
import GlobalMessage from "./GlobalMessage.js"; // 这里也可以直接执行 toastRegistry()Vue.use(GlobalMessage);
Use
this.$message('测试数据')
superconducting horse in the applet, which can be used globallythis.$message
, but I encountered another problem. There is no document
in the mini program. Let’s look at the uni-app
official document:
Then the requirements have to be fulfilled. We adopt another solution, using the vuex state machine for global state control, placing custom components on the required pages, and using the state machine to control the prompt content, display and hiding of messages. Note: Please install and configure vuex yourself.##uni-app
consists of two parts: the standard ECMAScript js API and the uni extension API.
Standard ECMAScript js is only the most basic js. The browser extends window, document, navigator and other objects based on it. The mini program also extends various wx.xx, my.xx, and swan.xx APIs based on standard js. Node also extends fs and other modules.
uni-app extends the uni object based on ECMAScript, and the API naming remains compatible with the applet. The js code of
uni-app, the h5 end runs in the browser. On the non-h5 end (including small programs and apps), the Android platform runs in the v8 engine, and the iOS platform runs in the jscore engine that comes with iOS. Neither of them runs in the browser or webview.
Non-H5 end, does not support the js API of window, document, navigator and other browsers
Globally registered components in main.js
import GlobalMessage from '@/components/common/GlobalMessage.vue'; Vue.component('GlobalMessage',GlobalMessage)
在需要的页面放置GlobalMessage
组件,但是我们需要每个页面都要加组件标签,实在是一个难以忍受的方式,于是在翻阅一些文档后,在jy文章中发现一个工具vue-inset-loader
我们来看该loader的提示:编译阶段在sfc模板指定位置插入自定义内容,适用于webpack构建的vue应用,常用于小程序需要全局引入组件的场景。(由于小程序没有开放根标签,没有办法在根标签下追加全局标签,所以要使用组件必须在当前页面引入组件标签),该插件刚好能够帮助我们全局追加组件标签。
npm install vue-inset-loader --save-dev
没有vue.config.js
请新建文件。
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') // }
"insetLoader": { "config":{ "message": "<GlobalMessage></GlobalMessage>", }, // 全局配置 "label":["confirm"], "rootEle":"div" }, "pages": [ { "path": "pages/tabbar/index/index", "style": { "navigationBarTitleText": "测试页面", // 单独配置,用法跟全局配置一致,优先级高于全局 "label": ["confirm","abc"], "rootEle":"div" } }, ]
config
(default: {}
) 定义标签名称和内容的键值对label
(default: []
) 需要全局引入的标签,打包后会在所有页面引入此标签rootEle
(default: "div"
) 根元素的标签类型,缺省值为div,支持正则,比如匹配任意标签 ".*"✔ label
和 rootEle
支持在单独页面的style里配置,优先级高于全局配置
虽然实现了全局消息的提示,但是在小程序中,该方法还是过于麻烦,需要在每个页面追加全局组件标签,希望大家有更好的方法能够不吝赐教。
推荐:《uniapp教程》
The above is the detailed content of Let's talk about how to use Uniapp to implement global message prompts and its components. For more information, please follow other related articles on the PHP Chinese website!