微信小程序云开发(6)— “增删改查综合案例(用户输入数据并动态添加到数据库)”

实际需求:

1.有用户输入数据的文本框和按钮
2.通过文本框的getName()和getValue()方法来获取用户输入的名称和值
3.有输入校验(输入为空时弹窗提醒用户)
4.通过按钮的add方法将数据传入到数据库中


1.demo.wxml

商品名:<input type="text" bindinput="getName"></input>
价格:<input type="text" bindinput="getValue"></input>
<button bindtap="add">点击添加商品</button>

<view wx:for="{
    
    {list}}">
  <view bindtap="click" data-id1="{
    
    {item._id}}">商品名:{
    
    {
    
    item.name}},价格:{
    
    {
    
    item.value}}</view>
</view>

效果:
在这里插入图片描述

2.demo.js

代码细节较多,仔细阅读

//全局变量
let Name=''
let Value=''
Page({
    
    
  data:{
    
    
    list:[]
  },

  onLoad(){
    
    
   this.getList()
  },
//专门写一个获取数据的getList方法,防止代码冗余
  getList(){
    
    
 wx.cloud.database().collection('goods')
 .get()
 .then(res=>{
    
    
   console.log('获取数据成功!',res.data)
   this.setData({
    
    
     list:res.data
   })
 })
 .catch(err=>{
    
    
   console.log('获取数据失败!')
 })
  },

  //实现点击(click)事件
  click(e){
    
    
    console.log('点击跳转商品详情',e.currentTarget.dataset.id1)
    //实现页面跳转并传递参数id到新页面
    wx.navigateTo({
    
    
      url: '/pages/demo1-1/demo1-1?id=' +e.currentTarget.dataset.id1,
    })
  },
  //获取用户输入的商品名
  getName(e){
    
    
    Name = e.detail.value
    console.log(Name)
  },
  //获取用户输入的商品价格
  getValue(e){
    
    
    Value = e.detail.value
    console.log(e.detail.value)
  },
  //点击按钮向数据库中添加数据
  add(){
    
    
    console.log('添加的商品名',Name)
    console.log('添加的商品价格',Value)
    //校验操作
    if (Name==''){
    
    
      //弹窗提醒函数
      wx.showToast({
    
    
        icon:'none', //为了去除弹窗中的√
        title: '商品名为空'
      })
    }
      else if(Value==''){
    
    
        wx.showToast({
    
    
          icon:'none',
          title: '价格为空'
        })
      }
    //添加操作
      else{
    
    
        wx.cloud.database().collection('goods')
        .add({
    
    
          data:{
    
    
          //将全局变量中的值传给name和value
            name:Name,
            value:Value
          }
        })
        .then(res=>{
    
    
          console.log('添加数据成功!')
          //再次向数据库发送请求,使列表动态更新数据
          this.getList()
        })
        .catch(err=>{
    
    
          console.log('添加数据失败!')
        })
      }
    

  }
})
  • 注意!
    下方showToast函数为弹窗的固定写法
    其中,为了去除弹窗中的“√” 故设置icon的值为none

wx.showToast({ icon:'none', title: '商品名为空' })


效果:

起始页面:
在这里插入图片描述
输入后点击按钮:
在这里插入图片描述
若输入为空,则弹窗提醒
1.商品名为空:
在这里插入图片描述
2.商品价格为空:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_47354826/article/details/119467096