uniapp小程序开发随笔

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

js小技巧

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

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;
    },
}

吸顶样式

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

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

        <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.https://www.csdn.net/tags/OtTaYgysMDI4OTUtYmxvZwO0O0OO0O0O.html

竖图使用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; //相机显隐。
          }
        },
      });
    },```
posted @ 2022-07-26 18:27  喜欢Tb  阅读(34)  评论(0)    收藏  举报  来源