微信小程序开发【八】-- 页面栈和模块化

系列文章目录

微信小程序开发【一】-- 初识小程序 传送门
微信小程序开发【二】-- 小程序入门 传送门
微信小程序开发【三】-- 项目结构概述 传送门
微信小程序开发【四】-- 配置详解 传送门
微信小程序开发【五】-- wxml详解 传送门
微信小程序开发【六】-- wxss详解 传送门
微信小程序开发【七】-- js详解 传送门
微信小程序开发【八】-- 页面栈和模块化 传送门
微信小程序开发【九】-- 初识小程序云开发 传送门
微信小程序开发【十】-- 云函数/云数据库/云存储 传送门



一、页面栈表现

在小程序中所有页面的路由全部由框架进行管理,而框架以栈的形式维护了当前的所有页面。
当发生路由切换时,页面栈的表现:

路由方式 页面栈表现
初始化 新页面入栈
打开新页面 新页面入栈
页面重定向 当前页面出栈,新页面入栈
页面返回 页面不断出栈,直到目标返回页,新页面入栈
Tab切换 页面全部出栈,只留下新的Tab页面
重加载 页面全部出栈,只留下新的页面
  • getCurrentPages() 用于获取当前页面栈的实例,可以把 getCurrentPages() 看做当前小程序所有页面的集合。该集合的第一个元素为首页,最后一个元素为当前页。
    ps:不要尝试修改页面栈,会导致路由以及页面状态错误。
// index/index.js ================================
Page({
    
    
  data:{
    
    "id":1,"name":"mirage"},
  onShow:function(){
    
    
    console.log(getCurrentPages().length);  // 输出 1
    console.log(getCurrentPages()[0].data); 
    // 输出 {id: 1, name: "mirage", __webviewId__: 24}
    console.log(getCurrentPages()[1]);
    // undefined
  },
  goto:function(){
    
    
    wx.navigateTo({
    
    
      url: "../info/info"
    })
  }
})

// info/info.js ==================================
Page({
    
    
  data: {
    
     "id": 2, "name": "fox"},
  onLoad: function (req) {
    
    
    console.log(getCurrentPages().length);  // 输出 2
    console.log(getCurrentPages()[0].data); 
    // {id: 1, name: "mirage", __webviewId__: 28}
    console.log(getCurrentPages()[1].data); 
    // {id: 2, name: "fox", __webviewId__: 29}
  }
})

//Page() 中 data 输出的 “” 每次打开页面该值为0
//每当页面重新加载 __webviewId__ 值 +1,且该值不可被手动修改。
//所以 __webviewId__  可以查看页面被加载的次数。

二、模块化

  • 小程序中所有 js 文件作用域皆为独立的,每一个 js 文件即为一个模块。模块与模块之间的引用通过 module.exports 或 exports 对外暴露接口。

注意:

  • exports 是 module.exports 的一个引用,因此在模块里边随意更改 exports 的指向会造成未知的错误。( 官方推荐使用 module.exports 来暴露模块接口 )
  • 小程序目前不支持直接引入 node_modules , 开发者需要使用到 node_modules 时候建议拷贝出相关的代码到小程序的目录中。
// common.js
function sayHello(name) {
    
    
  console.log(`Hello ${
      
      name} !`)
}
function sayGoodbye(name) {
    
    
  console.log(`Goodbye ${
      
      name} !`)
}

module.exports.sayHello = sayHello
exports.sayGoodbye = sayGoodbye

​在需要使用这些模块的文件中,使用 require 将公共代码引入

var common = require('common.js')
Page({
    
    
  helloMINA: function() {
    
    
    common.sayHello('MINA')
  },
  goodbyeMINA: function() {
    
    
    common.sayGoodbye('MINA')
  }
})
  • 文件作用域

在 JavaScript 文件中声明的变量和函数只在该文件中有效;不同的文件中可以声明相同名字的变量和函数,不会互相影响。

通过全局函数 getApp 可以获取全局的应用实例,如果需要全局的数据可以在 App() 中设置,如:

// app.js
App({
    
    
  globalData: 1
})
// a.js
// The localValue can only be used in file a.js.
var localValue = 'a'
// Get the app instance.
var app = getApp()
// Get the global data and change it.
app.globalData++
// b.js
// You can redefine localValue in file b.js, without interference with the localValue in a.js.
var localValue = 'b'
// If a.js it run before b.js, now the globalData shoule be 2.
console.log(getApp().globalData)

猜你喜欢

转载自blog.csdn.net/u011646838/article/details/130178909