微信小程序入门知识点

1、在wxml中只有用text标签包裹的文本才能在手机上长按选中

2、小程序的自适应单位是rpx,一般情况下不要使用px

3、每一个页面都是一个文件夹,下面的wxml、wxss、json、js文件最好和文件夹名称一致,这样在app.json中配置页面的时候只需一行即可

例如有一个welcome欢迎页面,那么我们如下操作:

在app.json中配置时,只需要一行即可完成这个页面的配置,同时也无需在wxml文件中引入对应的wxss样式文件

{
  "pages":[
    "pages/welcome/welcome"
  ]
}

4、每一个wxml文件实际上都隐藏了一个根节点page

5、不能在app.json中使用注释

6、text标签可以嵌套

如果我们想让一行文字显示不同的颜色,除了使用多个同级的text标签分别设置样式外,我们还可以使用text标签嵌套的方式

<text class='user-name'><text style='color:red'>Hello</text>,轻风起自远东</text>

上面这行代码就实现了Hello为红色,轻风起自远东为黑色的效果。

7、app.json中page下的第一个页面代表了小程序启动时显示的第一个页面

8、编写wxml布局时,使用弹性盒子模型的效率是最高的

9、js文件结构与Page页面的生命周期

在js文件中调用Page方法,会智能生成js的文件结构,其中包含了Page页面的生命周期函数,我们所有的方法和变量都需要在Page方法中完成

Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})

Page页面生命周期函数的执行顺序:onLoad(页面初始化)——onShow(页面显示)——onReady(页面渲染)——onHide(页面隐藏)——onUnload(页面关闭)

10、数据绑定小程序没有DOM节点,也不需要获取DOM节点就可以直接进行数据绑定

1、数据单向绑定

所谓单向绑定指的是数据只能从脚本文件单向传递到wxml文件,wxml文件无法改变脚本文件data对象中的数据

在脚本文件的data对象中写入数据,并在wxml中使用双花括号{{ }}进行调用

  data: {
        date: "Sep 18 2016",
        title: "这世界很酷@",
    },

调用如下:

<text>当前日期:{{date}}</text>

这里需要注意的是,如果是有引号的时候,不能把引号去掉,例如下面src属性是需要引号和双花括号同时存在的

<image src='{{post_img}}'></image>

2、数据动态绑定

从服务器获取数据一般在onLoad方法中实现,假设post_content1就是我们从服务器获取的数据,获取到数据之后我们需要调用this.setData(post_content1)将数据添加到data对象中

onLoad: function (options) {
        var post_content1 = {
            date: "Sep 18 2016",
            title: "正是虾肥蟹壮时",
            post_img: "/images/post/crab.png",
            content: "啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊,啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊,啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊阿啊啊啊啊啊",
            view_num: "112",
            collect_num: "96",
            author_img: "/images/avatar/1.png",
        };
        this.setData(post_content1);
    }

在wxml调用数据的方法和单向绑定是一样的,使用双花括号即可。

3、数据分离

在项目开发中,我们是不允许将数据存放在业务脚本中的,数据就是数据,业务就是业务,混杂在一起容易造成项目维护难度提升,耦合度提高,因此我们需要将数据单独分离出来。

创建一个新的data目录,在data目录下面创建一个专门用于存放数据的脚本文件posts-data.js,并将数据导出:

var local_database = [
    {
        date: "Sep 18 2016",
        title: "正是虾肥蟹壮时",
        imgSrc: "/images/post/crab.png",
        avatar: "/images/avatar/1.png",
        content: "啊啊啊啊啊啊啊啊啊啊啊啊",
        reading: "112",
        collection: "96",
    },
    {
        date: "Nov 25 2016",
        title: "比利·林恩的中场故事",
        imgSrc: "/images/post/crab.png",
        avatar: "/images/avatar/1.png",
        content: "啊啊啊啊啊啊啊啊啊",
        reading: "112",
        collection: "96",
    },
];

/*导出数据*/
module.exports = {
    postsList: local_database,
}

之后在业务脚本中通过require获取数据

/*不能用绝对路径,只能用相对路径*/
var postData = require('../../data/posts-data.js');

在onLoad中将数据绑定到data对象里

onLoad: function (options) {
        this.setData({
            posts_key: postData.postsList,
        });
    },

关于数组数据的循环获取可以参考13、wxml中的for循环

11、属性值为布尔值的特殊情况

我们有如下一个swiper组件,我们想令其水平滑动,因此需要将vertical设置为false

<swiper vertical='false' indicator-dots='true' autoplay='true' interval='5000'>

但是我们直接设置为false是无效的!因为小程序在解析字符串的时候会将其转换为布尔值,字符串“false”不为空,因此会被解析为true,如果我们想使用false的话需要使用到双花括号:

<swiper vertical='{{false}}' indicator-dots='true' autoplay='true' interval='5000'>

12、控制节点的显示和隐藏

控制节点的显示和隐藏我们需要使用微信小程序里的一个特殊属性wx:if

<!--隐藏-->
<image wx:if='{{false}}' class='post-author' src='/images/avatar/1.png'></image>
<!--显示-->
<image wx:if='{{true}}' class='post-author' src='/images/avatar/1.png'></image>

当然了,小程序中还有其他的写法例如:(为了优化小程序,提高加载速度,将三目操作代替wx:if)

<image wx:if='{{i===1}}' class='post-author' src='/images/avatar/1.png'></image>
<image wx:elif='{{i===2}}' class='post-author' src='/images/avatar/2.png'></image>
<image wx:else class='post-author' src='/images/avatar/3.png'></image>

这样写的意思就是如果i为1就显示1.png如果i为2就显示2.png否则就显示3.png

13、wxml中的for循环

有时我们需要将一个节点根据从服务器获取的数据多次显示,这时我们就需要用到wxml中的for循环来实现,我们从服务器获取的数据如下posts_content:

 onLoad: function (options) {
        //从服务器获取的以数组形式存放的数据
        var posts_content = [
            {
                date: "Sep 18 2016",
                title: "正是虾肥蟹壮时",
                post_img: "/images/post/crab.png",
                author_img: "/images/avatar/1.png",
                content: "啊啊啊啊啊啊啊啊啊啊",
                view_num: "112",
                collect_num: "96",
            },
            {
                date: "Nov 25 2016",
                title: "比利·林恩的中场故事",
                post_img: "/images/post/crab.png",
                author_img: "/images/avatar/1.png",
                content: "啊啊啊啊啊啊啊啊啊",
                view_num: "112",
                collect_num: "96",                
            }
        ];
        this.setData({
            posts_key: posts_content,
        });
    },

注意这里不能直接使用this.setData(posts_content)来将服务器获取的数组形式的数据放到data对象中,因为小程序会默认将posts_content的值直接复制粘贴到data中,如果我们这样做,实际上data对象会是如下形式:

   data: {
            {
                date: "Sep 18 2016",
                title: "正是虾肥蟹壮时",
                post_img: "/images/post/crab.png",
                author_img: "/images/avatar/1.png",
                content: "啊啊啊啊啊啊啊啊啊啊啊",
                view_num: "112",
                collect_num: "96",
            },
            {
                date: "Nov 25 2016",
                title: "比利·林恩的中场故事",
                post_img: "/images/post/crab.png",
                author_img: "/images/avatar/1.png",
                content: "啊啊啊啊啊啊啊啊啊",
                view_num: "112",
                collect_num: "96",                
            }
    },

这样就不再是一个数组的形式,也就无从在wxml中调用这些数据,因此我们需要使用下面这种形式,将posts_content数组存放在变量posts_key中

    this.setData({
        posts_key: posts_content,
     });

这样data对象就会是如下形式,这样我们就能在wxml文档中调用数组中的数据了。

data: {
    posts_key:[
       {
          date: "Sep 18 2016",
          title: "正是虾肥蟹壮时",
          post_img: "/images/post/crab.png",
          author_img: "/images/avatar/1.png",
          content: "啊啊啊啊啊啊啊啊",
          view_num: "112",
          collect_num: "96",
       },{
          date: "Nov 25 2016",
          title: "比利·林恩的中场故事",
          post_img: "/images/post/crab.png",
          author_img: "/images/avatar/1.png",
          content: "啊啊啊啊啊啊啊",
          view_num: "112",
          collect_num: "96",                
       }
    ]
},

下面我们在wxml中使用for循环,我们首先需要将需要循环显示的模块用block标签包裹起来,接着在block标签中设置对应的属性: 
wx:for属性需要赋与其一个存放数据的数组;而wx:for-item属性的值指代每个数组中的数据项,也可以不写,默认是item指代;wx:for-index的值指的是每个数据项在数组中的序号,从0开始,需要使用双花括号指代,也可以不写,默认是idx

<!--新闻列表-->
<block wx:for='{{posts_key}}' wx:for-item="item" wx:for-index="idx">
   <view class='post-container'>
      <view class='post-author-date'>
          <image class='post-author' src='{{item.author_img}}'></image>
          <text class='post-date'>{{item.date}}</text>
      </view>
      <text class='post-title'>{{item.title}}</text>
      <image class='post-image' src='{{item.post_img}}'></image>
      <text class='post-content'>{{item.content}}</text>
      <view class='post-like'>
        <image class='post-like-image' src='../../images/icon/chat.png'></image>
        <text class='post-like-font'>{{item.collect_num}}</text>
        <image class='post-like-image' src='../../images/icon/view.png'></image>
        <text class='post-like-font'>{{item.view_num}}</text>
      </view>
  </view>
</block>

14、页面跳转

wx.navigateTo()
wx.redirectTo()
wx.switchTab()
下面我们来详细了解一下三种方法的不同之处

wx.navigateTo指的是从父级页面跳转到子级页面,即跳转后的页面左上角有返回键
wx.redirectTo指的是平行跳转,即跳转后的页面左上角没有返回键
wx.switchTo指的是跳转到有tabbar的页面,上面两种方法无法跳转到有tabbar的页面

   onTap: function () {
        /*从父级页面跳转到子级页面,即跳转后的页面左上角有返回键*/
        wx.navigateTo({
             url: '../posts/post',
        });

        /*平行跳转,即跳转后的页面左上角没有返回键*/
        wx.redirectTo({
            url: '../posts/post',
        });

        wx.switchTab({
            url: "../posts/post"
        });
    },

15、事件机制--事件分为冒泡事件和非冒泡事件:

  1. 冒泡事件:当一个组件上的事件被触发后,该事件会向父节点传递。
  2. 非冒泡事件:当一个组件上的事件被触发后,该事件不会向父节点传递。

wxml中的冒泡事件列表:

  1. touchstart:手指触摸动作开始
  2. touchmove:手指触摸后移动
  3. touchcancel:手指触摸动作被打断,如来电提醒,弹窗
  4. touchend:手指触摸动作结束
  5. tap:手指触摸后马上离开
  6. longpress:手指触摸后,超过350ms再离开,如果指定了事件回调函数并触发了这个事件,tap事件将不被触发
  7. longtap:手指触摸后,超过350ms再离开(推荐使用longpress事件代替)
  8. transitionend:会在 WXSS transition 或 wx.createAnimation 动画结束后触发
  9. animationstart:会在一个 WXSS animation 动画开始时触发
  10. animationiteration:会在一个 WXSS animation 一次迭代结束时触发
  11. animationend:会在一个 WXSS animation 动画完成时触发

需要绑定事件的元素需要使用bind或者catch+事件名这样的属性:

<view class='moto-container' bindtap='onTap'>
  <text class='moto'>开启小程序之旅</text>
</view>

上面这串代码我们使用了bind+tap这样的属性来定义了一个手指点击触发onTap方法的事件

onTap: function (event) {
        ......
},

此外我们还需要了解一下bind和catch的区别,其实这两个的区别主要是在于冒泡事件和非冒泡事件。

首先我们将一个父节点及其子节点都使用bind绑定一个tap事件,父元素绑定onContainerTap(),子元素绑定onSubTap()

 <view class='moto-container' bindtap='onContainerTap'>
    <text class='moto' bindtap='onSubTap'>开启小程序之旅</text>
 </view>
onContainerTap:function (event) {
   console.log("excute onContainerTap");
},

onSubTap:function (event) {
   console.log("excute onSubTap");
},

这时我们点击子元素,查看控制台输出:

excute onSubTap
excute onContainerTap

我们发现不仅子元素的事件被执行了,其父元素的事件也被执行了。

那我们此时再将bind改为catch,点击子元素,查看控制台输出:

excute onSubTap

这时就只执行了子元素的事件,这就是bind和catch的区别,catch能阻止冒泡事件的冒泡。


16、template模板
template模板帮助我们实现了复用的思想,以13、wxml中的for循环为例,我们可以发现for循环中是一个新闻项的整体wxml代码,我们可以将这部分抽离成为一个独立的template模板,这样以后我们可以在任何地方直接调用这个template模板就能完成一个新闻项,而不需要将整个新闻项的wxml代码复制粘贴。

首先在页面文件夹下posts创建一个新文件夹posts-item用来存放模板文件,再在新文件夹下新建一个wxml和wxss文件,分别用来存放wxml模板和wxss模板。 

接着将for循环中的新闻项wxml代码剪切到模板wxml文件中,注意需要使用template标签包裹,并且需要为其name属性赋值,name属性关系到之后选择调用哪一个模板。

<!--post-item-template.wxml-->
<template name="postItem">
    <view class='post-container'>
        <view class='post-author-date'>
            <image class='post-author' src='{{item.avatar}}'></image>
            <text class='post-date'>{{item.date}}</text>
        </view>
        <text class='post-title'>{{item.title}}</text>
        <image class='post-image' src='{{item.imgSrc}}'></image>
        <text class='post-content'>{{item.content}}</text>
        <view class='post-like'>
            <image class='post-like-image' src='../../images/icon/chat.png'></image>
            <text class='post-like-font'>{{item.collection}}</text>
            <image class='post-like-image' src='../../images/icon/view.png'></image>
            <text class='post-like-font'>{{item.reading}}</text>
        </view>
    </view>
</template>

接着将这个新闻项对应的wxss样式代码也剪切到模板wxss文件中,这里就不需要再使用template标签包裹

/*post-item-template.wxss*/

/*新闻列表-作者头像和日期-容器*/
.post-author-date{
    margin: 10rpx 0 20rpx 10rpx;
}

/*新闻列表-作者头像和日期-作者头像*/
.post-author{
    width: 60rpx;
    height: 60rpx;
    /*垂直居中*/
    vertical-align: middle;
}

/*新闻列表-作者头像和日期-日期*/
.post-date{
    margin-left: 20rpx;
    /*垂直居中*/
    vertical-align: middle;
    margin-bottom: 5px;
    font-size: 26rpx;
}

/*新闻列表-新闻标题*/
.post-title{
    font-size: 34rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 10px;
    margin-left: 10px;
}

/*新闻列表-文章导图*/
.post-image{
    margin-left: 16px;
    width: 100%;
    height: 340rpx;
    margin: auto 0;
    margin-bottom: 15px;
}

/*新闻列表-文章内容*/
.post-content{
    color: #666;
    font-size: 28rpx;
    margin-bottom: 20rpx;
    margin-left: 20rpx;
    /*文本间距*/
    letter-spacing: 2rpx;
    line-height: 40rpx; 
}

/*新闻列表-喜欢和收藏-容器*/
.post-like{
    font-size: 13rpx;
    /*横向排列*/
    flex-direction: row;
    line-height: 16px; 
    margin-left: 10px;
}

/*新闻列表-喜欢和收藏-图片*/
.post-like-image{
    height: 16px;
    width: 16px;
    margin-right: 8px;
    vertical-align: middle;
}

/*新闻列表-喜欢和收藏-收藏和喜欢数*/
.post-like-font{
    vertical-align: middle;
    margin-right: 20px;
}

回到需要使用新闻项模板的wxml页面,在for循环中调用新闻项模板文件,is对应的就是template的name属性值,data属性对应的就是for循环数组的每一个子项,这样数组中的数据就能传递到模板文件中了。

注意不要忘了在开头引入模板文件

<import src="post-item/post-item-template.wxml"/>   
    ......
    ......
<!--新闻列表-->
<block wx:for='{{posts_key}}' wx:for-item="item" wx:for-index="idx">
   <!--template-->
   <template is="postItem" data="{{item}}"/>
</block>

同样的,在新闻项wxml对应的wxss文件中引入wxss模板:

@import "post-item/post-item-template.wxss";

这样我们就完成了template模板的生成和使用。

这里我们还需要学习一个知识,我们看下面两个地方

<!--post.wxml-->
<block wx:for='{{posts_key}}' wx:for-item="item" wx:for-index="idx">
   <!--template-->
   <template is="postItem" data="{{item}}"/>
</block>
<!--post-item-template.wxml-->
<template name="postItem">
    <view class='post-container'>
        <view class='post-author-date'>
            <image class='post-author' src='{{item.avatar}}'></image>
            <text class='post-date'>{{item.date}}</text>
        </view>
        <text class='post-title'>{{item.title}}</text>
        <image class='post-image' src='{{item.imgSrc}}'></image>
        <text class='post-content'>{{item.content}}</text>
        <view class='post-like'>
            <image class='post-like-image' src='../../images/icon/chat.png'></image>
            <text class='post-like-font'>{{item.collection}}</text>
            <image class='post-like-image' src='../../images/icon/view.png'></image>
            <text class='post-like-font'>{{item.reading}}</text>
        </view>
    </view>
</template>

我们会发现在template的wxml文件中我们使用item.来调用数据,如果我们不想要item.,而想直接输入变量名来调用数据的话,我们可以在调用模板的wxml文件中这样改:

<!--post.wxml-->
<block wx:for='{{posts_key}}' wx:for-item="item" wx:for-index="idx">
   <!--template-->
   <template is="postItem" data="{{...item}}"/>
</block>

在data属性的值前面加上… 这样的话就可以在模板文件中将item.去掉。

template模板是不能绑定事件的,因为template模板只是一个占位符,在编译的时候许会全部替换成模板里面的内容,如果我们要让template模板能响应事件,我们需要用一个容器view将其包裹,并在容器上绑定事件。


17、标签自定义属性

小程序中的自定义属性全部需要以data-开头,例如我要为下面的view标签增加一个自定义的postId属性:

<!--新闻列表-->
<block wx:for='{{posts_key}}' wx:for-item="item" wx:for-index="idx">
   <!--template-->
   <view catchtap="onPostTap" data-postId="{{item.postId}}">
      <template is="postItem" data="{{...item}}"/>
   </view>
</block>

并且小程序中的自定义属性在js中调用时会全部默认转换为小写字符!我们根据上面这串代码举个例子,首先在上面我们为view标签绑定了tap事件,我们现在实现点击view标签就输出其postId属性的值,完成对应的js代码:

onPostTap: function (event) {
   var postId = event.currentTarget.dataset.postid;
   console.log(postId);
},

我们发现在事件回调函数中调用自定义属性的值时我们用的是postid而不是postId!用postId是错误的!

18、页面之间的数据传递

如果从一个页面跳转到另一个页面的同时也想传递一个数据过去,那么实现方法如下:

在跳转的页面url后加上?[要传递的变量]=[值]

示例代码如下:点击绑定了这个tap事件的标签后,从当前页面跳转到post-detail页面时携带一个名为postid的变量传递过去。

onPostTap: function (event) {
   var postId = event.currentTarget.dataset.postid;
   //跳转到新闻详情页面
   wx.navigateTo({
      url: 'post-detail/post-detail?postid=' + postId,
   })
},

那么在post-detail页面中获取这个变量的方式则是:

onLoad:function (option) {
  var postId = option.postid;
}

19、缓存---小程序中的缓存共有八种方法

  1. wx.setStorageSync(key, value)——同步缓存
  2. wx.setStorage(object)——异步缓存
  3. wx.getStorageSync(key)——同步取缓存
  4. wx.getStorage(object)——异步取缓存
  5. wx.removeStorageSync(key)——同步清除缓存
  6. wx.removeStorage(object)——异步清除缓存
  7. wx.clearStorageSync()——同步清除所有缓存
  8. wx.clearStorage()——异步清除所有缓存

示例代码:

wx.setStorageSync('key', 'value')

wx.setStorage({
  key:"key",
  data:"value"
})

var value = wx.getStorageSync('key')

wx.getStorage({
  key: 'key',
  success: function(res) {
      console.log(res.data)
  } 
})

wx.removeStorageSync('key')

wx.removeStorage({
  key: 'key',
  success: function(res) {
    console.log(res.data)
  } 
})

wx.clearStorageSync()

wx.clearStorage()

小程序中的缓存若不手动清除将永久存在,但是缓存最大上限为10MB。

20、界面交互反馈

小程序里的吐司的API:

wx.showToast(OBJECT)

//示例代码:
wx.showToast({
  title: '成功',
  icon: 'success',
  duration: 2000
});

相当于Android中的Toast。

显示​模态弹窗的API:

wx.showModal(OBJECT)

//示例代码
wx.showModal({
  title: '提示',
  content: '这是一个模态弹窗',
  success: function(res) {
    if (res.confirm) {
      console.log('用户点击确定')
    } else if (res.cancel) {
      console.log('用户点击取消')
    }
  }
})

显示操作菜单的API:

wx.showActionSheet(OBJECT)

//示例代码
wx.showActionSheet({
  itemList: ['第一项', '第二项', '第三项'],
  success: function(res) {
    console.log(res.tapIndex)
  },
  fail: function(res) {
    console.log(res.errMsg)
  }
})

21、动态图片的两种方式

(1)、使用wx:if标签

<!--根据当前文章的收藏情况collected显示不同的收藏图标-->
<image wx:if="{{collected}}" catchtap='onCollectionTap' src='/images/icon/collection.png'></image>
<image wx:else catchtap='onCollectionTap' src='/images/icon/collection-anti.png'></image>

上面的代码实现了根据data对象中collected的值来判断应该显示哪一张图片,具体对于collected值的操作在js脚本中完成,这里不赘述。

(2)、三目运算符  (为了提高加载速度尽量将wx:if代替)

<image catchtap='onCollectionTap' src='{{collected?"/images/icon/collection.png":"/images/icon/collection-anti.png"}}'></image>

上面的代码实现了根据data对象中collected的值来判断应该显示哪一张图片,具体对于collected值的操作在js脚本中完成,但是使用的是三目运算符的方式,需要注意的是src的值外面如果是单引号,那么里面需要用双引号,如果外面是双引号,那么里面就得用单引号。

22、在小程序里若要动态改变前端显示,一般是通过js代码动态修改data对象里的数据,前端通过data对象的数据来进行不同的显示。

23、小程序应用的生命周期

在app.js文件中输入App,智能感知生成如下代码,其中含有整个小程序应用的生命周期函数:

App({
    /**
     * 当小程序初始化完成时,会触发 onLaunch(全局只触发一次)
     */
    onLaunch: function () {

    },

    /**
     * 当小程序启动,或从后台进入前台显示,会触发 onShow
     */
    onShow: function (options) {

    },

    /**
     * 当小程序从前台进入后台,会触发 onHide
     */
    onHide: function () {

    },

    /**
     * 当小程序发生脚本错误,或者 api 调用失败时,会触发 onError 并带上错误信息
     */
    onError: function (msg) {

    },
});

24、全局变量

在app.js中调用App方法,传入一个对象,这个对象就是在整个小程序中都能调用的全局对象,我们为这个对象增加一个属性。

//app.js
App({
    globalData: {
        //全局变量,用来标示音乐是否在播放
        g_isPlayingMusic: false,
    },
});

那么如果我们要在其他的js文件中调用这个属性,我们首先需要在Page方法之前,获取到这个全局对象

//从app.json中获取全局对象
var app = getApp();

Page({
    ......
    //调用全局对象中的属性
    var isPlayingMusic = app.globalData.g_isPlayingMusic;
});

25、target和currentTarget---target指的是当前点击的组件,currentTarget指的是事件捕获的组件。

现在有下面这样一个Swiper轮播图组件,现在我想实现点击轮播图后获取到对应的轮播图的自定义属性postId,可是此时我们发现catchTap是绑定在Swiper上而不是image组件上,我们无法通过event.currentTarget.dataset.postid在响应事件函数onSwiperTap中获取到,这是因为currentTarget指的是Swiper这个事件捕获的组件而不是image,我们要想获得postId这个自定义属性的值,我们需要使用event.target.dataset.postid。
 

<!--滑块视图容器——轮播组件-->
<swiper catchtap='onSwiperTap' class='swiper' indicator-dots='true' autoplay='true' interval='5000'>
    <!--轮播子项-->
    <swiper-item>
        <image src='/images/post/xiaolong.jpg' data-postId="3"></image>
    </swiper-item>
    <swiper-item>
       <image src='/images/post/vr.png' data-postId="4"></image>  
    </swiper-item>
    <swiper-item>
       <image src='/images/post/crab.png' data-postId='5'></image>  
    </swiper-item>
</swiper>
    onSwiperTap:function (event) {
        var postId = event.target.dataset.postid;
    },

26、动态设置导航栏标题

微信小程序提供了一组api动态设置导航栏标题:

wx.setNavigationBarTitle(OBJECT)
//示例代码
wx.setNavigationBarTitle({
  title: '当前页面'
})

需要注意的是,onLoad方法里是不允许对界面UI进行操作的,因为只有运行到onReady()才表示界面UI渲染完成,因此如果我们要动态设置导航栏标题,需要在onReady或其后面的生命周期函数中调用这个api,否则不会生效。


27、上滑加载更多的两种方式

1、利用组件scroll-view

scroll-view组件有一个bindscrolltolower属性,绑定一个回调函数即可,当上滑到底部时就会自动触发这个函数。注意要想实现上滑下载更多的功能,需要为scroll-view设置高度,否则无效。

<scroll-view scroll-y="true" scroll-x="false" bindscrolltolower = "onScrollLower">
    ....
</scroll-view>
onScrollLower: function (event) {
        ...
}

2、利用函数onReachBottom

MINA在Page里还提供了一个onReachBottom事件,使用这个事件来监听页面上滑到底。

 onReachBottom: function (event) {
    ...
  },

28、获取input组件中输入的内容

小程序中没有DOM的概念,无法通过获取到input组件实例来获取其内容,因此需要利用事件的机制来获取。

//onBindConfirm:用户点击确认后回调的方法
<input type='text' bindconfirm='onBindConfirm'></input>
onBindConfirm: function (event) {
   //获取input搜索框输入的内容
   var text = event.detail.value;
},
  1.  

29、子页面调用公共js对象以便调用其方法

子页面想调用共公js的方法,需先在子页面js中先实例化app:具体过程如下: app.js中写子页面需要调用的公共方法

App({
  // 自定义公共方法
  commonFunction:function(){
      return "公共方法"
    }
})

在需要调用的子页面中,

var app = getApp();  //先实例化应用
// console.log(app)  //可查看公共app.js里面的方法
Page({
  data: {
  "label":app.commonFunction()  //子页面中调用公共appjs的方法
  }
})

30、善用于公共模板(templeate)

1、在公共模板中定义template元素,利用 方法 ,这种方式只会显示公共模板的template里面的内容,之外的内容不会显示.

<!--wxml-->
<import src='公共模板地址'/>
<template is='模板里面template定义的name名称' data='{{引入的数据1,引入数据2}}'></template>

注意:这里的data=’{{引入的数据1,引入数据2}}’ 是在template中要提取js文件中的data数据里面的key名字,否则无法显示。
公共模板的wxml:在公共模板中必须定义每一个template的的name的名字,否则引用的时候无法得知引用具体某一个;

<!--必须有有name不然import方式无法判断到底要引用哪一个tempalte-->
<template name='header'>
    <!--这个数据只是提取要引用的文件的里面js里面定义的对应的数据,如果在其他文件中定义不在要引用的文件中无效-->
    {{title.header}}
</template>

要引用的文件js定义数据:

data: {
    title:{
        header:'这是template的header部分',
        footer:'这是template的footer部分',
        other:'这是tempalt外部部分'
    }
}

2、方式二

<include src="公共模板地址"/>
这种方式是引入了模板中除了tempalte以外的所有内容。
<include src="../../template/footer.wxml"/> 
公共模板的wxml:
 
{{title.other}}
js定义的数据:

 title:{header:'news里面的的header',footer:'这是template的footer部分'}

总结:import方式和imclude方式的不同在于前者仅引用公共模板中的template里面的内容后者仅引用template以外的内容,显而易见,include方式更简单一些,在wxml中只需要一句话即可。

31、锚点定位

<!--index.wxml-->
<view class="container">
<!--品牌-->
<scroll-view scroll-y="true" scroll-into-view="{{toView}}"> 
  <view wx:for="{{citysMap}}">
    <view class="ncq-smal" id="{{index}}">
      {{index}}
    </view>
    <view wx:for="{{item}}" wx:for-item="citys" class="ncq-box" 
         data-cityname="{{citys.city_name}}" bindtap="cityNameClick">
            <label class="ncq-brand-name">{{citys.city_name}}</label>
    </view>
  </view>
</scroll-view>
 <!--  字母导航-->
    <view class="ncq-fixe-nav">
            <view  wx:for="{{citysMap}}" data-letter="{{index}}" bindtap="rightZmClick">
                <label>{{index}}</label> 
            </view>
    </view>
   <!-- 字母导航end-->
</view>
 //字母锚链定位
  topZmClick: function (event) {
    var letter = event.currentTarget.dataset.letter;
    this.setData({
      toView: letter
    })
  },
scroll-view {
  height: 600px;
}

注:scroll-view必须要设置高度,不然无效

32、广告轮播

微信小程序广告轮播元素 图片所在元素 <swiper-item>其中属性有:

  autoplay:true,//是否自动播放
   autoplaytxt:"停止自动播放",
   indicatorDots: true,//指示点
   // indicator-color:"white",//指示点颜色 暂未启动
   // indicator-active-color:"red",//当前选中的指示点颜色暂未启动
   indicatorDotstxt:"隐藏指示灯",
   interval: 1000,//图片切换间隔时间
   duration: 500,//每个图片滑动速度,
   circular:true,//是否采用衔接滑动
   current:3,//初始化时第一个显示的图片 下标值(从0)index

图片更改事件:bindchange=‘imgchange’ imagechange()的e.detail.current为当前显示页面的下标值

1、在index.wxml中操作如下:

<swiper bindchange="imgchange" indicatorDots='{{indicatorDots}}' current='{{current}}' autoplay='{{autoplay}}' interval='{{interval}}'duration='{{duration}}' circular='{{circular}}'>
    <block wx:for='{{imgUrls}}'>
    <swiper-item>
        <image style="" mode="" src="{{item}}" binderror="" bindload="" class='swiper-img'></image>
    </swiper-item>
    </block>
</swiper>
<button  bindtap="autoplaychange" >{{autoplaytxt}}</button>

2、在index.wxss中操作如下:

.swiper-img{
    width: 100%;
    height: 500rpx;
}

3、在index.js中操作如下:

Page({
  data: {
    imgUrls: [
      '../../img/3.jpg',//图片src
      '../../img/6.jpg',
      '../../img/5.jpg',
      '../../img/4.jpg'
    ],
    autoplay:true,//是否自动播放
    autoplaytxt:"停止自动播放",
    indicatorDots: true,//指示点
    // indicator-color:"white",//指示点颜色 暂未启动
    // indicator-active-color:"red",//当前选中的指示点颜色暂未启动
    indicatorDotstxt:"隐藏指示灯",
    interval: 1000,//图片切换间隔时间
    duration: 500,//每个图片滑动速度,
    circular:true,//是否采用衔接滑动
    current:3,//初始化时第一个显示的图片 下标值(从0)index
  },
  autoplaychange:function(event){//停止、播放按钮
    if (this.data.autoplaytxt=="停止自动播放") {
      this.setData({
        autoplaytxt:"开始自动播放",
        autoplay:!this.data.autoplay
      })
    }else{
       this.setData({
        autoplaytxt:"停止自动播放",
        autoplay:!this.data.autoplay
      })
    };
  },
  imgchange:function(e){//监听图片改变函数
console.log(e.detail.current)//获取当前显示图片的下标值
  }
})

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值