uniapp 开发记录

240 阅读2分钟

使用微信开发者工具,公众号模式调试网页(微信授权登录)

/*
 appid  对应公众号的 appid
 redirect_uri  对应的 页面
*/ 
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx21750d59dc3e8a6e&redirect_uri=http://convwx-dev.clear-sz.com/pages/auth/index

uniapp H5 通过url参数修改样式(修改主题色)

1、在 App.vue 页面进行参数获取与变量存储

onLaunch(options) {
	console.log("获取url上面的参数对象", options);
	
	//主题颜色
	this.setConfig('color',options?.query?.color,'--label-primary-color');
	
	//主题背景颜色
	this.setConfig('bgcolor',options?.query?.bgcolor,'--label-primary-bg-color');
	// 基础字体大小
	this.setConfig('fontSizeBase',options?.query?.fontSizeBase,'--font-size-base');
	this.setConfig('fontSizeSm',options?.query?.fontSizeBase,'--font-size-sm');
	this.setConfig('fontSizeLg',options?.query?.fontSizeLlg,'--font-size-lg');
	this.setConfig('fontSizeLlg',options?.query?.fontSizeLlg,'--font-size-llg');
},

getElementsByTagName() 方法可返回带有指定标签名的对象的集合。

setProperty() 方法用于设置一个新的 CSS 属性,同时也可以修改 CSS 声明块中已存在的属性。

var() 函数用于插入自定义的属性值,如果一个属性值在多处被使用,该方法就很有用。

methods: {
	/* 
		type: 类型
		data: 数据
		variable: 变量(class名称)
	 */
	setConfig(type, data, variable) {
		if (data || uni.getStorageSync(type)) {
			if (data && data !== uni.getStorageSync(type)) {
                                // 在 body 上面新增 CSS 属性(style)
				window.document.getElementsByTagName('body')[0].style.setProperty(variable, data);
				uni.setStorageSync(type, data)
			} else {
				window.document.getElementsByTagName('body')[0].style.setProperty(variable, data || uni
					.getStorageSync(type));
				uni.setStorageSync(type, data || uni.getStorageSync(type))
			}
		}
	}
},

2、url 上面的参数挂在 body 上面

image.png

3、在scss变量文件 variables.scss

image.png

4、将scss变量 variables.scss 注入到 App.vue

image.png

5、在页面中使用 scss 变量

image.png

根据主题色修改 uviewui 组件 颜色

src/mixins/theme.js

import store from "@/store";
import Vue from 'vue';
Vue.mixin({
    data(){
        return {}
    },
    onShow() {
        // 这里与上面 在 `App.vue` 页面进行参数获取与变量存储 同理 只是不同写法
        this.$nextTick(() => {
            //#ifdef H5
            document.getElementsByTagName('body')[0].style.setProperty('--theme-primary-color', this.themeMainColor);
            //#endif
            //#ifndef H5
            // 创建节点查询
            let query = uni.createSelectorQuery().in(this);
            console.log("query", query.select(`home-page`));
            //#endif
        });
    },
    computed: {
        themeMainColor() {
            // 主题颜色可以是从后端配置,通过接口获取,存入到缓存中(主题颜色值 如:#3071EA)
            return store.getters.themeMainColor; 
        },
        // 监听缓存主题色的变化
        $primary() {
            return this.themeMainColor;
        },
        $inNumBgColor(){
            return '#12CE8A'
        },
    },
});

在页面上引入 src/mixins/theme.js , 通过 computed 动态监听 theme.js 中的 $primary 主体变量 image.png

使用

image.png

image.png

公共样式

mixin


// 一行文本溢出
@mixin ellipsis_1($width) {
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-text-overflow: ellipsis;
  -moz-text-overflow: ellipsis;
  white-space: nowrap;
  width: $width;
}

//多行文本溢出
@mixin morelineEllipsis($line:2) {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: $line;
  autoprefixer: off;
  -webkit-box-orient: vertical;
  autoprefixer: on;
  word-break: break-all;
}

/*1px边框*/
@mixin border-1px($color:$u-border-color,$direction:top,$left:0) {
  position: relative;
  &:after {
    position: absolute;
    /* #ifndef APP-NVUE */
    box-sizing: border-box;
    content: ' ';
    pointer-events: none;
    @if $direction == top {
      border-bottom: 1px solid $color;
      right: 0;
      left: $left;
      top: 0;
    } @else if $direction == bottom {
      border-bottom: 1px solid $color;
      right: 0;
      left: $left;
      bottom: 0;
    }
    /* #endif */
  }
  @media (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5) {
    &::after {
      -webkit-transform: scaleY(0.7);
      transform: scaleY(0.7)
    }
  }

  @media (-webkit-min-device-pixel-ratio: 2), (min-device-pixel-ratio: 2) {
    &::after {
      -webkit-transform: scaleY(0.5);
      transform: scaleY(0.5)
    }
  }
  @media (-webkit-min-device-pixel-ratio: 3), (min-device-pixel-ratio: 3) {
    &::after {
      -webkit-transform: scaleY(0.333);
      transform: scaleY(0.333)
    }
  }
}

/*1px (上下左右)边框*/
@mixin all-border-1px($color:$line,$border-radius:8rpx){
  position: relative;
  &::after{
    content: ' ';
    position: absolute;
    pointer-events: none;
    box-sizing: border-box;
    -webkit-transform-origin: 0 0;
    transform-origin: 0 0;
    left: 0;
    top: 0;
    border: 1px solid $color;
    border-radius: $border-radius;
  }
  @media (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5) {
    &::after {
      width: 150%;
      height: 150%;
      -webkit-transform: scale(0.7, 0.7);
      transform: scale(0.7, 0.7);
    }
  }

  @media (-webkit-min-device-pixel-ratio: 2), (min-device-pixel-ratio: 2) {
    &::after {
      width: 200%;
      height: 200%;
      -webkit-transform: scale(0.5, 0.5);
      transform: scale(0.5, 0.5);
    }
  }
  @media (-webkit-min-device-pixel-ratio: 3), (min-device-pixel-ratio: 3) {
    &::after {
      width: 300%;
      height: 300%;
      -webkit-transform: scale(0.333, 0.333);
      transform: scale(0.333, 0.333);
    }
  }
}

/*取消1px边框*/
@mixin border-none() {
  &:after {
    display: none;
  }
}

样式兼容

iphoneX 底部安全区适配

小程序利用safe-area-inset-*兼容iPhoneX

uviewui iphoneX 底部安全区适配

uni-app 全面屏、刘海屏适配(iphoneX适配)及安全区设置

uni.uploadFile 在h5下上传blob文件无法获取文件名后缀

uni.uploadFile 在h5下上传blob文件链接的时候无法获取文件名后缀

/**
 * 上传图片
 * @param params url:请求地址,filePath:文件路径,data:额外参数
 * @returns 服务器返回数据
 */
uploadImg(url, filePath, data) {  
        let token = uni.getStorageSync('token');  
        return new Promise((resolve, reject) => {  
            const blobUrl = filePath  
            // 通过XMLHttpRequest对象将Blob链接转换为Blob对象  
            const xhr = new XMLHttpRequest();  
            xhr.open('GET', blobUrl);  
            xhr.responseType = 'blob';  
            xhr.onload = () => {  
                var blob = xhr.response;  
                var ext = blob.type.split('/').pop(); // 获取文件的后缀  
                const file = new File([xhr.response], 'filename.'+ext, {type: blob.type});  

                // 创建FormData对象并将文件和其他参数添加到其中  
                const formData = new FormData();  
                formData.append('file', file);  

                Object.keys(data).forEach(key => {  
                    console.log(key, data[key]);  
                    formData.append(key, data[key]);  
                });  

                // 使用axios上传文件  
                axios.post(url, formData, {  
                    headers: {  
                        'Token'      : token,  
                        'Content-Type': 'multipart/form-data'  
                    }  
                }).then(response => {  
                    resolve(response.data)  
                }).catch(error => {  
                    reject(error)  
                });  
            };  
            xhr.send();  
        })  
    },
// 使用

let val = {
  fileName: "1.png",
  filename: "1.png",
  name: "1.png",
};

let data = await uploadImg(this.$api.jd_file_server_fileupload, filePath, val);

if (data.code != 200) {
  uni.showToast({
    title: data.message || "系统异常",
    icon: "none",
  });
  return;
}     

清除缓存(微信公众号h5、钉钉微应用)

1、在 nginx 配置 增加以下配置

add_header Cache-Control "private, no-store, no-cache, must-revalidate, proxy-revalidate";

image.png

2、控制页面不被缓存

<!-- HTTP 1.1 -->
<meta http-equiv="pragma" content="no-cache">
<!-- HTTP 1.0 -->
<meta http-equiv="cache-control" content="no-cache">
<!-- Prevent caching at the proxy server -->
<meta http-equiv="expires" content="0">
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9" />

image.png

支付宝环境

u-form 不能写class,不生效

textarea 自带 length

024e80b0c01923e020e832b3083a23bb.png

uview ui

Cell 单元格

设置u-cell-item 样式

  • 使用 title-style (用来设置特殊个别的样式)
<u-cell-group>
	<u-cell-item  title="个人设置" :arrow="false" :title-style="cellItemStyle"> 
		<u-switch slot="right-icon" v-model="checked"></u-switch>  
	</u-cell-item>
</u-cell-group>
data() {
    return {
        cellItemStyle:{
            'color': '#999999','fontSize':'32rpx'
        }
    };
},
  • v-deep(统一设置)
<style lang="scss" scoped>
	::v-deep .u-cell_title{
		color: #999999;
		font-size:32rpx;
	}
</style>