15

微信小程序的全局弹窗以及全局实例 - fanction

 1 year ago
source link: https://www.cnblogs.com/wang-fan-w/p/17149755.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

微信小程序的全局弹窗以及全局实例

微信小程序组件关系中,父组件使用子组件需要在父组件index.json中引入子组件,然后在父组件页面中使用,这种组件的对应状态是一对一的,一个组件对应一个页面。如果有一个全局弹窗(登录),那么每个页面引入一次组件会非常麻烦,这里就需要封装全局弹窗,在页面直接引入使用即可。

微信小程序提供全局组件,只需要在app.json中引入组件,该组件就会被注册为全局组件,父组件的json文件不需要引入组件即可使用。

在这里插入图片描述
  "usingComponents": {
    "whatStore": "/components/whatStore/index"
  },

usingComponents中注册的组件就是全局组件,在小程序的任意页面都可以引入并使用组件

在这里插入图片描述

直接将组件写入页面即可,组件的使用方法和普通组件一致。

App(Object object)

在这里插入图片描述

App()必须在app.js中调用,必须调用并且全局只能调用一次,在App()中有应用的的生命周期。全局函数可以写在App()中,通过getApp()获取App()上挂载的方法。

在这里插入图片描述
// 页面上使用
let app = getApp()
console.log(app.sayHi());  // 全局函数
在这里插入图片描述

可以在App()上挂载登录方法,当用户token过期或者未登录时,通过全局函数配合全局弹窗来发起登录,也可以只调用全局函数默认刷新token

getApp()

在这里插入图片描述

getApp()上定义的参数为全局参数,都可以在小程序任意页面直接使用,建议将参数添加到globalData上。

// A页面
let app = getApp()
app.globalData.params = '全局参数'

// B页面
let app = getApp()
console.log(app.globalData.params )  // 全局参数

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK