微信小程序学习笔记【2】

78 阅读1分钟

TODO-LIST应用

bind:input="onInputValue" 绑定输入内容

<input type="text" class="m-input" bind:input="onInputValue" value="{{inputValue}}" placeholder="请输入内容"/>

bind:tap="onConfirm" 绑定点击事件

<button type="primary" bind:tap="onConfirm">确定</button>

显示内容

<view>
    <view wx:for="{{list}}" wx:key="index" class="v-view">
    {{item.id}}-{{item.name}}-{{item.price}} 
        // 绑定删除事件
        <button bind:tap="onDelete" data-pricce="{{item.price}}" data-id="{{item.id}}">删除</button>
    </view>
</view>

逻辑

列表数据

 data:{
    inputValue:'',//输入框内容
    list:[
        // {id:1001,name:'数据结构',price:20},
        // {id:1002,name:'计算机组成原理',price:40},
        // {id:1003,name:'计算机网络',price:60},
        // {id:1004,name:'操作系统',price:80}
    ]//列表数据
},

绑定输入框事件

onInputValue(e){
    let inputValue = e.detail.value//输入框内容
    this.setData({inputValue})
},

确定事件,获取输入框内容添加显示到列表界面

onConfirm(){
    let name = this.data.inputValue//获取输入值
    // 随机生成id
    let id = Math.floor(Math.random()*(9999-1000)+1000)
    // 随机生成价格
    let price = Math.floor(Math.random()*100)
    // 构建商品对象
    let product = {id,name,price}
    // 获取列表数据
    let list = this.data.list
    
    list.push(product)
    // inputValue置空
    this.setData({list,inputValue:''})
},

删除事件

1获取id
2通过id找商品在数组里的索引号
3splice(index,1) slice(start,end)
在原数组上操作    根据索引号返回新数组

代码片段

onDelete(e){
    // 1获取id
    let id = e.target.dataset.id
    // 2根据id找索引号
    let list = this.data.list
    // 3findIndex遍历数组查找满足条件的索引号
    let index = list.findIndex(item=>item.id == id)
    // 4删除
    list.splice(index,1)
    // 5更新界面
    this.setData({list})
}

结果如图

wechatdevtools_2d2RJMxrL2.png