微信小程序入门、目录结构配置、逻辑层注册程序和注册页面、作用范围及模块化、视图层、数据绑定、for循环、事件处理

2022/1/4 17:09:13

本文主要是介绍微信小程序入门、目录结构配置、逻辑层注册程序和注册页面、作用范围及模块化、视图层、数据绑定、for循环、事件处理,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1 小程序入门

1.app.js的代码如下:

// app.js
App({
  onLaunch() {
    // 展示本地存储能力
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      }
    })
  },
  // 全局的属性
  globalData: {
    userInfo: null
  }
})

如图所示:在这里插入图片描述
2.app.json的代码如下:

{
  "pages":[
    "pages/index/index",
    "pages/logs/logs"
  ],
  "window":{
    "backgroundTextStyle":"light",
    "navigationBarBackgroundColor": "#fff",    
    "navigationBarTitleText": "微信",
    "navigationBarTextStyle":"black"
  },
  "style": "v2",
  "sitemapLocation": "sitemap.json"
}

如图所示:在这里插入图片描述
3.app.wxss的代码如下:

// 全局css文件
/**app.wxss**/
.container {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  padding: 200rpx 0;
  box-sizing: border-box;
} 

如图所示:在这里插入图片描述
4. index.js的代码如下:

// index.js
// 获取应用实例
const app = getApp()

Page({
  data: {
    motto: 'Hello Adair',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    canIUseGetUserProfile: false,
    canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName') // 如需尝试获取用户信息可改为false
  },
  // 事件处理函数
  bindViewTap() {
    // 页面跳转
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  // 当页面加载之后执行的
  onl oad() {
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认,开发者妥善保管用户快速填写的头像昵称,避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },
  getUserInfo(e) {
    // 不推荐使用getUserInfo获取用户信息,预计自2021年4月13日起,getUserInfo将不再弹出弹窗,并直接返回匿名的用户个人信息
    console.log(e)
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  }
})

如图所示:在这里插入图片描述
5.index.wxml的代码如下:

<!--index.wxml-->
<view class="container">
  <view class="userinfo">
    <block wx:if="{{canIUseOpenData}}">
      <view class="userinfo-avatar" bindtap="bindViewTap">
        <open-data type="userAvatarUrl"></open-data>
      </view>
      <open-data type="userNickName"></open-data>
    </block>
    <block wx:elif="{{!hasUserInfo}}">
      <button wx:if="{{canIUseGetUserProfile}}" bindtap="getUserProfile"> 获取头像昵称 </button>
      <button wx:elif="{{canIUse}}" open-type="getUserInfo" bindgetuserinfo="getUserInfo"> 获取头像昵称 </button>
      <view wx:else> 请使用1.4.4及以上版本基础库 </view>
    </block>
    <block wx:else>
      <image bindtap="bindViewTap" class="userinfo-avatar" src="{{userInfo.avatarUrl}}" mode="cover"></image>
      <text class="userinfo-nickname">{{userInfo.nickName}}</text>
    </block>
  </view>
  <view class="usermotto">
    <text class="user-motto">{{motto}}</text>
  </view>
</view>

如图所示:在这里插入图片描述

2 目录结构配置

1.修改index.wxml的代码如下:

<!--index.wxml-->
<view class="container">
  <view bindtap="bindViewTap" class="userinfo">
    <block wx:if="{{canIUseOpenData}}">
      <view class="userinfo-avatar" bindtap="bindViewTap">
        <open-data type="userAvatarUrl"></open-data>
      </view>
      <open-data type="userNickName"></open-data>
    </block>
    <block wx:elif="{{!hasUserInfo}}">
      <button wx:if="{{canIUseGetUserProfile}}" bindtap="getUserProfile"> 获取头像昵称 </button>
      <button wx:elif="{{canIUse}}" open-type="getUserInfo" bindgetuserinfo="getUserInfo"> 获取头像昵称 </button>
      <view wx:else> 请使用1.4.4及以上版本基础库 </view>
    </block>
    <block wx:else>
      <image bindtap="bindViewTap" class="userinfo-avatar" src="{{userInfo.avatarUrl}}" mode="cover"></image>
      <text class="userinfo-nickname">{{userInfo.nickName}}</text>
    </block>
  </view>
  <view class="usermotto">
    <text class="user-motto">{{motto}}</text>
    <button bindtap="changeMotto">点击</button>
  </view>
</view>

如图所示:在这里插入图片描述
2.修改index.js的代码如下:

  changeMotto() {
    this.setData({
      motto:"你好!忙里偷闲!"
    });
  },

如图所示:在这里插入图片描述
项目的目录结构如图所示:
在这里插入图片描述
1.app.js:处理小程序的全局逻辑。
2.app.json:放置小程序的公共设置。
3.app.wxss:放置公共样式表。
4.修改app.json的代码如下:

{
  "pages":[
    "pages/index/index",
    "pages/logs/logs",
    "pages/test/test"
  ],
  "window":{
    "backgroundTextStyle":"light",
    "navigationBarBackgroundColor": "#fff",    
    "navigationBarTitleText": "微信",
    "navigationBarTextStyle":"black"
  },
  "tabBar": {
    "color": "#ccc",
    "selectedColor": "green",
    "list": [{
      "pagePath": "pages/index/index",
      "text": "首页",
      "iconPath": "image/featured.png",
      "selectedIconPath": "image/featured-actived.png"
    },
    {
    "pagePath": "pages/test/test",
    "text": "测试页",
    "iconPath": "image/profile.png",
    "selectedIconPath": "image/profile-actived.png"
  },  
    {
      "pagePath": "pages/logs/logs",
      "text": "日志",
      "iconPath": "image/search.png",
      "selectedIconPath": "image/search-actived.png"
    }
   ]
  },
  "debug": true,
  "style": "v2",
  "sitemapLocation": "sitemap.json"
}

如图所示:在这里插入图片描述

3 逻辑层注册程序和注册页面

1.编写test.wxml的代码如下:

<view>{{name}}</view>
<view>密码是:{{pass}}</view>
<button bindtap="toIndex">跳转到navi</button>
<navigator hover-class= "active" url="../navi/navi">跳转到navi</navigator>

如图所示:
在这里插入图片描述
2.编写test.js的代码如下:

// 获取应用的实例
var app = getApp();
Page({
    data:{
    name:"Adair",
    pass:null
    },
    toIndex:function(){
        wx.navigateTo({
          url: "../navi/navi",
          success:function(){
            console.log("跳转到navi成功!")
          },
        });
    },
    onl oad:function(options){
        this.setData({
            pass:app.globalData.pass
        });
    },
    onReady:function(){
        // 页面渲染完成
    },
    onShow:function(){
        // 页面显示

    },
    onHide:function(){
        // 页面隐藏

    },
    onUnload:function(){
        // 页面关闭
    }
})

如图所示:在这里插入图片描述
3.编写test.wxss的代码如下:

.active{
    color:red;
}

如图所示:在这里插入图片描述
4.编写navi.wxml的代码如下:

<view>我是navi.wxml页</view>
<button bindtap="back">返回</button>

如图所示:在这里插入图片描述
5.编写navi.js的代码如下:

Page({
    back:function(){
        wx.navigateBack();
    }
})

如图所示:在这里插入图片描述
6.修改app.json的代码如图所示:在这里插入图片描述
在这里插入图片描述

4 作用范围及模块化

1.编写common.js的代码如下:

console.log("我是common.js")
function sayHello(name){
    console.log('Hello ' + name + '!')
}
module.exports ={
     sayHello:sayHello
}

如图所示:在这里插入图片描述
2.编写test.wxml的代码如下:

<!-- <view>{{name}}</view>
<view>密码是:{{pass}}</view>
<button bindtap="toIndex">跳转到navi</button>
<navigator hover-class= "active" url="../navi/navi">跳转到navi</navigator> -->
<button bindtap="say">say hello!</button>

如图所示:在这里插入图片描述
3.编写test.js的代码如下:

var common = require("../../common/common.js")
   say:function(){
        common.sayHello(this.data.name)
    },

如图所示:在这里插入图片描述

5 视图层

1.编写test.wxml的代码如下:

<view id="{{id}}">内容</view>
<!--条件渲染-->
<button bindtap="show">显示隐藏</button>
<view wx:if="{{condition}}">条件渲染显示</view>
<view wx:if="{{ id == 1}}">第一条</view>
<view wx:elif="{{ id>1}}">第二条</view>
<view wx:else="{{ id>4}}">我是第4条</view>

如图所示:在这里插入图片描述
2.编写test.js的代码如下:

   show:function(){
        var condition = this.data.condition;
        this.setData({
            condition: !condition
        });
    },

如图所示:在这里插入图片描述

6 数据绑定

1.编写test.wxml的代码如下:

<block wx:if="{{false}}">
    <view>第一个view</view>
    <view>第二个view</view>
</block>
<!--hidden在view上是不生效 在text生效-->
<text hidden="{{true}}">我是一段文本</text>
<view>{{condition?"正":"反"}}</view>
<view>{{id-3}}</view>
<!--字符串连接-->
<view>{{"hello " + name}}</view>
<view wx:for="{{arr}}">{{item}}</view>
<!--组合-->
<view wx:for="{{[id,5,4,3,2,1]}}">{{item}}</view>
<!--定义一个模板-->
<!--模板拥有独立作用域-->
<template name="object">
    <view>{{a}}</view>
    <view>{{b}}</view>
    <view>{{name}}</view>
</template>
<!--使用模板-->
<template is="object" data="{{a:1,b:2,name:name,}}"></template>
<template is="object" data="{{...obj}}"></template>

如图所示:在这里插入图片描述
2.编写test.js的代码如下:

arr:[1,2,3,4,5,6],
    obj:{
        a:5,
        b:2
    }

如图所示:在这里插入图片描述

7 for循环

1.编写test.wxml的代码如下:

<view wx:for="{{arr}}" wx:for-index="i" wx:for-item="itemName">{{i}}:{{itemName}}</view>
<!--行-->
<view wx:for="{{[1,2,3,4,5,6,7,8,9]}}" wx:for-item="i">
    <view style="display:inline-block; width: 50px;" wx:for="{{[1,2,3,4,5,6,7,8,9]}}" wx:for-item="j">
            <View wx:if="{{j <= i}}">
                {{i}} * {{j}} = {{i*j}}
            </View>
    </view>
</view>

如图所示:在这里插入图片描述

8 小程序事件处理

8.1 冒泡事件

1.编写test.wxml的代码如下:

<!--事件-->
<view id="outter" style="border: 1px solid red;">
    outter view 
    <view id="middle" style="border: 1px solid green;" bindtap="middleTap">
        moddle view 
        <view id="inner" bindtap="innerTap">
            inner view 
        </view>
    </view>
</view>

如图所示:在这里插入图片描述
2.编写test.js的代码如下:

  innerTap:function(){
        console.log("触发了inner的tap事件")
    },
    middleTap:function(){
        console.log("触发了middle的tap事件")
    },

如图所示:在这里插入图片描述
阻止冒泡,把bindtap修改catch即可!



这篇关于微信小程序入门、目录结构配置、逻辑层注册程序和注册页面、作用范围及模块化、视图层、数据绑定、for循环、事件处理的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程