this关键字与数据绑定 / 小程序设计与开发 #8

Words
93
Reading
1 min
Listen
Play
5y

this关键字

this就是属性或方法“当前”所在的对象。
函数都是在某个对象之中运行,this就是函数运行时所在的对象(环境)。
函数f在全局环境执行,this.x指向全局环境的x;在obj环境执行,this.x指向obj.x。

var person = {
  name: '张三',
  describe: function () {
    return '姓名:'+ this.name;
  }
};

数据绑定

使js
 

1. 
<text>{{message}}</text>

//js 直接赋值
date:{message:hello world}

使this.setData
  onLoad: function (options) {
    //(onLoad是页面自动加载的,里面的函数会自动调用)
    this.setData({
      title: 'Set some data for updating view.'
   })
   //this.data.title = 'Set some data for updating view.'
 },

2. 
<view bindtap="viewTap"></view>

//js
Page({
  viewTap() {
    console.log('view tap')
  }
})

3. 
<block wx:for="{{news}}" wx:for-item="item" wx:key="index">
  <view class='news-item'>
        <view>{{index}}:{{item.name}}</view>
  </view>
</block>
  
  <view wx:for="{{news}}">
    {{ item.name }}
  </view>

.js
data:{
  news: [
      { name: "商品1" },
      { name: "商品2"}
    ]
}

eg:

 <block wx:for="{{video}}" wx:for-item="item" xw:key="index">
     <view class='chaptertitle'>{{item.chapter}}</view>
            <view class='video'>
            <block wx:for="{{video[index].section}}" wx:for-item="item" xw:key="index">
                <view class='chapter'>
                    {{item.name}}
                  </view>
                </view>
            </block>
     </view>
</block>
//js
  onLoad: function (options) {
    let db = wx.cloud.database();
    db.collection("course").where({
      title: options.title
    }).get().then(res => {
      console.log(778, res);
      this.setData({
        course:res.data[0],
        video: res.data[0].video
        });
      console.log(779, res.data[0].video)
    })
  },

input输入绑定

eg1:
<input bindinput="accountInput" placeholder="用户名/邮箱/手机号"/>
//js
accountInput:function(e){
  let content = e.detail.value
  console.log(content)
},

//数据双向绑定
<input model:value="{{value}}" />

eg2:
<input bindblur="pwdBlur" placeholder="请输入密码" password />
//js
pwdBlur:function(e){
  let password = e.detail.value
  if(password != ''){
    this.setData({password:password})
  }
}