uniapp小程序开发随笔

js逻辑

数组是这样的fatherdata.value.selectFilm[fatherdata.value.curr].schedules
fatherdata.value.scheduleId,这是需要比对的数据源,如果比对的数据源fatherdata.scheduleId是数组id第一位则返回为空,否则则取数据源在数组中的前一位id作为返回值

  // 获取要比对的数据源和数组
  const scheduleId = fatherdata.value.scheduleId;
  const schedules =
    fatherdata.value.selectFilm[fatherdata.value.curr].schedules;
  // 如果数组为空,返回空
  if (schedules.length === 0) {
    return null;
  }
  // 获取数组中的第一个元素的 ID
  const firstScheduleId = schedules[0].id;
  // 如果比对的数据源是数组中的第一个元素的 ID,则返回空
  if (scheduleId === firstScheduleId) {
    return null;
  }
  // 寻找比对的数据源在数组中的前一位 ID
  let previousId = null;
  for (let i = 1; i < schedules.length; i++) {
    if (schedules[i].id === scheduleId) {
      previousId = schedules[i - 1].id;
      break;
    }
  }
  return previousId;

css部分

  //可滚动盒子
  overflow-y: auto;
  overflow-x: hidden;
  //css回到顶部平滑过渡(给大盒子加上)
  scroll-behavior: smooth;
  //css三角
  https://s1.ax1x.com/2022/12/26/zxrhRJ.png
  width: 0;
  height: 0;
  border-top: 50px solid skyblue;
  border-right: 50px solid transparent;
  border-left: 50px solid transparent;
  //等比例
  aspect-ratio: 16/9;
  //超出变成省略号
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  //超出两行变成省略号
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  text-overflow: ellipsis;
  //网站全灰-----
  html {
      filter: grayscale(100%);
      -webkit-filter: grayscale(100%);
    } 
    (1) 限定关键词:用双引号""包裹
    (2) 限定标题:intitle
    (3) 限定内容:intext
    (4) 限定网址:inurl 
    (5) 限定网站:site
    (6) 限定图片大小:imagesize
    (7) 限定文件类型:filetype

  

js小技巧

JSON.parse('') //字符串转json
substr(0, 2) === 'is' //前端判断前两位是否一样
//需求:安卓webview调试前端h5的全局函数(接受参数修改本地参数)
//在 index.html
    var listen = {};
    function CallFun(params) {
      listen[params.action](params.data);
    }
// vue文件中(不需要监听 可实时更改!!!!!)
  mounted() {
    window.listen['setVolume'] = (res) => {
      audio.volume = res.volume;
    };
   }
//本地json
import fixedData from "@/static/seatLove.json";
//js动画
function animation(duration, from, to, onProgress) {
    let value = from;
    const speed = (to - from) / duration;
    const start = Date.now();
    function _run() {
        const t = Date.now() - start;
        if (t >= duration) {
            value = to;
            onProgress(value);
            return;
        }
        value = from + t * speed;
        onProgress(value);
        requestAnimationFrame(_run);
    }
    _run();
}

animation(2000, 4000,30, val => {
    console.log(val);
});
//uni中
function animation(duration, from, to, onProgress) {
  let value = from;
  const distance = to - from;
  const fps = 60; // 设置帧率为60帧每秒,可以根据需要调整
  const interval = 1000 / fps; // 计算每帧之间的间隔时间
  const steps = duration / interval; // 计算总共需要多少帧
  let frame = 0; // 当前帧数
  function _run() {
    frame++;
    if (frame >= steps) {
      value = to;
      onProgress(value);
      return;
    }
    value = from + distance * (frame / steps);
    onProgress(value);
    setTimeout(_run, interval);
  }
  _run();
}

git相关

//.gitignore忽略文件不生效解决办法(清除本地缓存)
git rm -r --cached .
git add .
git commit -m 'update .gitignore'

手机号授权登录

      <button
        class="anniu_wx"
        open-type="getPhoneNumber"
        @getphonenumber="onGetPhoneNumber"
      >
        <view>微信授权登录</view>
      </button>
      onLoad(){
      //拿到登录所需的code
      this.getcode()
      }
  method:{
    getcode() {
      let that = this;
      uni.login({
        success(res) {
          that.code = res.code;
        },
      });
    },
        //手机号授权
    onGetPhoneNumber(res) {
    //尽量用这个去判断允许还是拒绝,否则可能会有灵异bug
      if (res.detail.errMsg != "getPhoneNumber:ok") {
        //拒绝授权后弹出一些提示
        return;
      } else {
        uni.showLoading({
          title: "登录中...",
        });
        let data;
        let iv = res.detail.iv;
        let encdata = res.detail.encryptedData;
        data = {
          code: this.code,
          encryptedData: encdata,
          iv: iv,
        };
        api.login(data).then((res) => {
          console.log(res, 200);
          uni.setStorageSync("token", res.data.token);
          uni.hideLoading();
          uni.reLaunch({
            url: "/pages/home/home",
          });
        });
      }
    },
}

可滑动视图

    <swiper :current="curr" @change="setCurr">
      <swiper-item v-for="item in list" :key="item.id">
        <scroll-view>
        {{item}}
        </scroll-view>
      </swiper-item>
    </swiper>
    
  data(){
    return{
    //展示第一个
      curr: 0,
}
method:{
    setCurr(e) {
    //手动操作,如果需求有点击切换也是操作这个curr
      this.curr = e.detail.current;
    },
}
//禁止滑动
<swiper>
 <swiper-item @touchmove.stop="touchable"></swiper-item>
</swiper>

const touchable = () => {
  return false;
};

吸顶样式

  position: sticky;
  top:0;

使用自定义导航栏Navbar后下拉刷新样式会被遮挡解决方案

官方也给出了解决方式,我就是采用的这个,然后他的文档需要仔细看(去点击它这个插件解决点击查看

防止请求中用户乱点

//1.最简单的
      uni.showLoading({
        title: "开启中...",
        //增加遮罩层就可以了
        mask: true,
      });
//2.css解决
<view :class="jyzt ? 'jinyong' : ''"></view>
data(){
return{
//默认关闭,触发请求为true,成功后改为false
  jyzt:false
}
}
//css
.jinyong {
  pointer-events: none;
}
//🈲止用户滑动
@touchmove.stop.prevent="disabledScroll"

当没有保存按钮的时候保存

        <uni-list-item title="开检前置时间">
          <template v-slot:footer>
            <view class="input_box">
              <input
                @click="bg(name)"
                @blur="blur"
                type="number"
                v-model="name"
              />
              <view>分钟</view>
            </view>
          </template>
        </uni-list-item>
       //input,那就失去焦点保存,点击事件是为了保存它的旧值防止重复请求
    bg(e) {
      this.old = e;
    },
    blur(e) {
      if (e.detail.value != this.old) {
        this.name = e.detail.value;
        this.save();
      }
    },

请求封装

const host = "http://192.168.2.88:8001";

const request = (url = "", method = "", data = {}) => {
  let token = uni.getStorageSync("token")
    ? " Bearer " + uni.getStorageSync("token")
    : "";
  let role = uni.getStorageSync("role");
  const c = {
    CinemaApiToken: token,
  };
  const ad = {
    AdvertiserApiToken: token,
  };
  return new Promise((resolve, rej) => {
    console.log(c, 231);
    uni.request({
      // header: {
      // },
      //这里后端需要两个token所以这样写,不用就改成普通的
      header: role == "cinema" ? c : ad,
      method: method,
      url: host + url,
      data: data,
      success: function (res) {
        if (res.data.code == 0) {
          resolve(res.data);
        } else {
        //处理token过期
          if (res.data.errorMessage == "管理员未登录") {
            uni.showToast({
              title: res.data.errorMessage,
              icon: "none",
            });
            uni.removeStorageSync("token");
            setTimeout(function () {
              uni.reLaunch({
                url: "/pages/login/login",
              });
            }, 1000);
          } else {
            uni.showToast({
              title: res.data.errorMessage,
              icon: "none",
            });
          }
          rej(res);
        }
      },
      fail: function (error) {
        if (error.errMsg == "request:fail timeout") {
          uni.showToast({
            title: "请求超时,请重试!",
            duration: 2000,
            icon: "none",
          });
        } else if (error.errMsg == "request:fail ") {
          uni.showToast({
            title: "无网络请移动到有网络的地方重试!",
            duration: 2000,
            icon: "none",
          });
        } else {
          uni.showToast({
            title: error.errMsg,
            duration: 2000,
            icon: "none",
          });
        }
        rej(error);
      },
    });
  });
};
export default request;

api.js
import request from "./request.js";

module.exports = {
  // 授权
  login(data) {
    return request("/auth/login/", "post", data);
  },
}

递归请求

  beforeDestroy() {
    clearTimeout(this.timer);
  },
  
save() {
      this.timer = null;
      uni.showLoading({
        title: "保存中...",
        mask: true,
      });
      api.changeAnyCofig(this.obj.ids, this.cofig).then((res) => {
        this.id = res.data;
        this.Getcode(this.id);
      });
    },
    // 递归
    Getcode(id) {
      api.Getcode(this.obj.ids, id).then((res) => {
        if (res.data == true) {
          uni.hideLoading();
          uni.showToast({
            title: "已完成",
            duration: 2000,
          });
          this.ih = 0;
          return;
        } else {
        //ih为次数,data自己定义,我这是请求10,记得重置
          if (this.ih == 10) {
            uni.showToast({
              title: "操作失败",
              icon: "error",
              duration: 2000,
            });
            this.ih = 0;
          } else {
            let that = this;
            //每秒一次,自增
            this.timer = setTimeout(function () {
              ++that.ih;
              that.Getcode(that.id);
            }, 1000);
          }
        }
      });
    },

正则

//手机号
if (!/^1[3456789]\d{9}$/.test(this.ipone)) {
//不正确
}
//邮箱
    checkEmail(email) {
      return RegExp(
        /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/
      ).test(email);
    }
    if (!this.checkEmail(this.email)) {
    //不正确
    }

跳转传参

//1.单个的话就把  + "&ooo=" + this.name, 这句话删掉,多个可以往后加,也可以使用方法2
      uni.navigateTo({
        url: "../terminal/terminal?item=" + this.id + "&ooo=" + this.name,
      });
//2.对象
       uni.navigateTo({
          url:
            "/pages/shopdetails/shopdetails?item=" +
            encodeURIComponent(JSON.stringify(data)),
        });
       const item = JSON.parse(decodeURIComponent(e.item));

竖图使用canvas重绘旋转铺满盒子

      <image
        @click="lookimg(obj)"
        class="rotateAfter"
        show-menu-by-longpress
        :src="rotateAfter"
      ></image>
      <canvas
        canvas-id="my-canvas"
        style="width:{{canvasWidth}}px;height:{{canvasHeight}}px;position:absolute;top:-2000%;"
      >
      </canvas>
data{
    ...
      obj: {},
      a:[],
      rotateAfter: null,
      canvasWidth: null,
      canvasHeight: null,
 }

methods:{
    cs(img) {
      let _this = this;
      uni.getImageInfo({
        src: img, //网络图片路径
        success(res) {
          console.log(res);
          let canvasContext = uni.createCanvasContext("my-canvas", _this);
          // 下面按比例写死宽度高度是为了压缩图片提升上传速度,可按实际需求更改
          let width = 500;
          let height = 500;
          if (res.orientation) {
              _this.canvasWidth = width;
              _this.canvasHeight = height;
              canvasContext.translate(height / 2, width / 2);
              canvasContext.rotate((270 * Math.PI) / 180);
              canvasContext.drawImage(
                res.path,
                -width / 2,
                -height / 2,
                width,
                height
              );
          }
          canvasContext.draw(false, () => {
            uni.canvasToTempFilePath(
              {
                canvasId: "my-canvas",
                success(res) {
                  let filePath = res.tempFilePath;
                  _this.rotateAfter = filePath;
                },
              },
              _this
            );
          });
        },
      });
    },
 接口(){
     let that = this
     that.obj = res.data
     setTimeout(function () {
            that.cs(res.data.Url);
         }, 1000);
       },
   lookimg(e) {
      if (this.a.length == 0) {
        this.a.push(e.hUrl, e.Url);
      }
      uni.previewImage({
        urls: this.a,
      });
    },
}

相机授权,拒绝之后可以再次申请权限

  onShow() {
    this.GetAuthority();
  },
    GetAuthority() {
      let that = this;
      uni.getSetting({
        success(res) {
          if (!res.authSetting["scope.camera"]) {
            uni.authorize({
              scope: "scope.camera",
              success(res) {
                // 授权成功
                uni.showToast({
                  title: "授权成功",
                  icon: "none",
                });
                that.isShow = true;
              },
              fail() {
                uni.showModal({
                  content: "检测到您没打开获取相机功能权限,是否去设置打开?",
                  confirmText: "确认",
                  cancelText: "取消",
                  success: (res) => {
                    if (res.confirm) {
                      uni.openSetting({
                        success: (res) => {},
                        fail: (err) => {
                          console.log(err);
                        },
                      });
                    } else {
                      uni.showToast({
                        title: "获取授权相机授权失败",
                        icon: "none",
                        success: function () {
                          uni.navigateBack();
                        },
                      });
                    }
                  },
                });
              },
            });
          } else {
            that.isShow = true; //相机显隐。
          }
        },
      });
    },```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值