Home > Web Front-end > uni-app > body text

Let's talk about how to use Uniapp to implement global message prompts and its components

青灯夜游
Release: 2022-06-22 22:00:54
forward
6646 people have browsed it

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!

Let's talk about how to use Uniapp to implement global message prompts and its components

#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.

Implementation

1. Short polling request-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)	
    }
Copy after login

2. Global message prompt component

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.

(1) Define a GlobalMessage.vue component

Customize a message prompt component, text will be the prompt message parameter we passed in

<template>
	<div class=&#39;message-container&#39;>
		全局消息提示 {{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>
Copy after login

(2) Create a new GlobalMessage.js

Introduce the custom component, vue.extendYou can use the basic Vue constructor to create a child Class, parameter is an object containing components. The object example is as follows:

{
template:&#39;&#39;,
data(){
    return {
        属性
    }
  }
}
Copy after login

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(&#39;div&#39;),data(){
			return {text:text,
			}
		}
	})document.body.appendChild(MessageDom.$el)
}
Copy after login

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
Copy after login

GlobalMessage.js all code

import vue from "vue"
import GlobalMessage from  &#39;./GlobalMessage.vue&#39;;
const MessageConstructor= vue.extend(GlobalMessage)
function showMessage(text,duration){
	const MessageDom=new MessageConstructor({
		el:document.createElement(&#39;div&#39;),data(){
			return {text:text,
			}
		}
	})
	document.body.appendChild(MessageDom.$el)
}
function registryMessage(){
	vue.prototype.$message=showMessage
}
export default registryMessage
Copy after login

(3)

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);
Copy after login

Use

this.$message(&#39;测试数据&#39;)
Copy after login

3. How to implement

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:

# The js API of

##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

uni-app’s js API

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.

Globally registered components in main.js

import GlobalMessage from &#39;@/components/common/GlobalMessage.vue&#39;;
Vue.component(&#39;GlobalMessage&#39;,GlobalMessage)
Copy after login

在需要的页面放置GlobalMessage组件,但是我们需要每个页面都要加组件标签,实在是一个难以忍受的方式,于是在翻阅一些文档后,在jy文章中发现一个工具vue-inset-loader

4.vue-inset-loader的使用

我们来看该loader的提示:编译阶段在sfc模板指定位置插入自定义内容,适用于webpack构建的vue应用,常用于小程序需要全局引入组件的场景。(由于小程序没有开放根标签,没有办法在根标签下追加全局标签,所以要使用组件必须在当前页面引入组件标签),该插件刚好能够帮助我们全局追加组件标签。

vue-inset-loader

(1)安装

npm install vue-inset-loader --save-dev

(2)vue.config.js注入loader

没有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,&#39;./src/pages.json&#39;)
// }
Copy after login

(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"
        }
    },
]
Copy after login
  1. 配置说明
  • 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!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!