一、完成效果
二、制作流程
1.在小程序根目录下新建一个common文件夹,在该文件夹下新建common.js文件.
// common.js const comMsg = '来自不同目录下模块的变量' function comFunc() { return '来自不同目录下模块的函数' } // 导出模块的变量和函数 module.exports = { comMsg, comFunc }2.在index文件夹下新增模块文件my-index.js
// my-index.js const myIndexMsg = '来自相同目录下不同模块的变量' function myIndexFunc() { return '来自相同目录下不同模块的函数' } module.exports = { myIndexMsg, myIndexFunc }3.修改app.js文件
// app.js App({ appMsg: '来自全局模块的变量', appFunc() { return '来自全局模块的函数' } })4.修改index.js文件
// index.js const indexMsg = '来自本模块的变量' function indexFunc() { return '来自本模块的函数' } // 获取到小程序全局唯一的 App 实例。 const app = getApp() // 引入模块common。返回common模块通过 module.exports 或 exports 暴露的接口 const comm = require('../../common/common.js') // 引入模块my-index。返回my-index模块通过 module.exports 或 exports 暴露的接口 const myIndex = require('my-index.js') Page({ data: { // 使用app.js文件中的变量和函数 msg1: 'index.js模块引用' + app.appMsg, msg2: 'index.js模块引用' + app.appFunc(), // 使用common.js文件中的变量和函数 msg3: 'index.js模块引用' + comm.comMsg, msg4: 'index.js模块引用' + comm.comFunc(), // 使用my-index.js文件中的变量和函数 msg5: 'index.js模块引用' + myIndex.myIndexMsg, msg6: 'index.js模块引用' + myIndex.myIndexFunc(), // 使用本模块的变量和函数 msg7: 'index.js模块引用' + indexMsg, msg8: 'index.js模块引用' + indexFunc() } })5.修改index.wxml文件
<!--index.wxml--> <navigation-bar title="模块化" back="{{false}}" color="black" background="#FFF"></navigation-bar> <scroll-view class="scrollarea" scroll-y type="list"> <view class="box"> <view class="title">引用来自不同模块的变量和函数</view> <!-- app.js 全局模块 --> <view class="bg-blue">{{msg1}}</view> <view class="bg-blue">{{msg2}}</view> <!-- common.js 不同目录模块 --> <view class="bg-yellow">{{msg3}}</view> <view class="bg-yellow">{{msg4}}</view> <!-- my-index.js 相同目录模块 --> <view class="bg-purple">{{msg5}}</view> <view class="bg-purple">{{msg6}}</view> <!-- index.js 本模块 --> <view class="bg-green">{{msg7}}</view> <view class="bg-green">{{msg8}}</view> </view> </scroll-view>6.修改index.wxss文件
/**index.wxss**/ page { height: 100vh; display: flex; flex-direction: column; } .scrollarea { flex: 1; overflow-y: hidden; } view { line-height: 2em; font-size: 40rpx; } /* --- 以下为新增的纯背景颜色(柔和护眼) --- */ /* 1. 全局模块:淡蓝色 */ .bg-blue { background-color: #e6f4ff; } /* 2. 不同目录模块:淡黄色 */ .bg-yellow { background-color: #fffbe6; } /* 3. 相同目录模块:淡紫色 */ .bg-purple { background-color: #f9f0ff; } /* 4. 本模块:淡绿色 */ .bg-green { background-color: #f6ffed; }7.修改app.wxss文件
/**app.wxss**/ .container { height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: space-between; padding: 200rpx 0; box-sizing: border-box; } /**app.wxss**/ .box { /* 设置外边距 */ margin: 20rpx; /* 设置内边距 */ padding: 20rpx; /* 设置边框 */ border: 2rpx solid silver; } .title { /* 设置字体大小 */ font-size: 40rpx; /* 设置字体加粗 */ font-weight: bolder; /* 设置居中对齐 */ text-align: center; /* 设置下外边框 */ margin-bottom: 30rpx; /* 设置字体颜色 */ color: red; }三、知识要点
四、个人总结
希望可以坚持学下去