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

in STEEM CN/中文3 years ago

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})
  }
}

Coin Marketplace

STEEM 0.17
TRX 0.16
JST 0.029
BTC 60323.94
ETH 2395.54
USDT 1.00
SBD 2.54