VUE3 项目踩坑

创建项目

vue create projectName

选择手动 Manually select features 默认配置,选择需要的默认配置
在这里插入图片描述

cd projectName              // 进入到项目根目录
npm run serve  				// 启动项目

vue3引入vant

//引入
npm i vant@next -S
//main.js
import Vant from 'vant';
import 'vant/lib/index.css';
const app = createApp(App)
app.use(Vant)

在 vue.config.js 中 改变页面适配比例,页面在浏览器中px会自动转为rem,适配移动端

//vue.config.js

module.exports = {
  css: {
    sourceMap: false,
    loaderOptions: {
      postcss: {
        plugins: [
          autoprefixer(),
          pxtorem({
            rootValue: 37.5,
            propList: ["*"],
          }),
        ],
      },
    },
  },
 }

还可以利用babel-plugin-import自动按需引入组件
.babelrc中添加配置 ,
相关配置参考vant 官网

vue3中setup 使用

export default {
  setup () {
  //数据的储存
    const state = reactive({
      message: '',
      msgList: []
    })
       //路由的使用
    const router = useRouter()
    let username = ''
 
    onMounted(() => {
      username = localStorage.getItem('username')
      if (!username) {
        router.push('/login')
        return
      }
    })
    // 函数的使用
    const onSendMessage = () => {
      const { message } = state
      if (!message.trim().length) return
      state.msgList.push({
        id: new Date().getTime(),
        user: username,
        dateTime: new Date().getTime(),
        message: state.message
      })
      state.message = ''
    }
    //输出值
    return {
      ...toRefs(state),
      onSendMessage
    }
  }
}


vue3实现拍照压缩上传

html


 <input class="chooseImg" type="file" ref="fileBtn1"  @change="takePhoto()" accept="image/*"/>

script function

 async takePhoto() {
      var that = this;
      const inputFile = await this.$refs.fileBtn.files[0];
      // let res;
      console.log("选了图片");
      console.log(inputFile);
      this.inputFile = inputFile;
      if (this.inputFile) {
        let inputFile = this.inputFile;
        if (
          inputFile.type !== "image/jpeg" &&
          inputFile.type !== "image/png" &&
          inputFile.type !== "image/gif"
        ) {
          alert("不是有效的图片文件!");
          return;
        }
        const reader = new FileReader();
        const res = reader.readAsDataURL(this.inputFile);
        reader.onloadend = function () {
          var strBase64 = reader.result.substring(0);
          that.imgSrc = strBase64;
          console.log(res);
          var imageFron = new Image();
          imageFron.src = that.imgSrc;
          imageFron.onload = function () {
            that.idCardBase1 = that.compress(imageFron);
            console.log(that.idCardBase1, "that.idCardBase1");
        
          };
        };
      } else {
        return;
      }
    },

压缩方案(上文中调用)

 compress(img) {
      var width = img.width;
      var height = img.height;
      // 如果图片大于一百万像素,计算压缩比例值50万以下
      var ratio = (width * height) / 500000;
      if (ratio > 1) {
        ratio = Math.sqrt(ratio);
        width /= ratio;
        height /= ratio;
      }
      var canvas = document.createElement("canvas");
      var ctx = canvas.getContext("2d");

      canvas.width = width;
      canvas.height = height;
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      //清屏
      ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
      var pic = canvas.toDataURL("image/jpeg", 0.7);
      return pic;
    },

收付款(vue3引入条形码,二维码)

1.二维码

引用 qrcodejs2

npm i qrcodejs2 -s

页面中引入:

import QRCode from 'qrcodejs2';


qrcode() {
			this.$refs.qrCodeUrl.innerHTML = ''; // 清空之前生成的二维码内容
			var qrcode = new QRCode(this.$refs.qrCodeUrl, {
				text: this.data, // 需要转换为二维码的内容
				width: 140,
				height: 140,
				colorDark: '#000000',
				colorLight: '#ffffff',
				correctLevel: QRCode.CorrectLevel.H
			});
			console.log(qrcode);
		},

this.data 是从接口拿到的字符串,调用函数将字符串转成二维码

//调用
JsBarcode('#barcode', this.data); //
this.qrcode();
<div class="qrcode" ref="qrCodeUrl"></div>

2.条形码

引入

npm i jsbarcode -s 

//在页面中按需引入
import JsBarcode from 'jsbarcode';

在页面中写入

<svg id="barcode"></svg>

引入方法 this.data 代表拿到的字符串

// 条形码
		barcode() {
			var JsBarcode = require('jsbarcode');
			let barCode = this.data;
			JsBarcode('#barcode', this.data, {
				format: 'CODE128', //选择要使用的条形码类型
				text: barCode, //显示文本
				displayValue: false, //是否在条形码下方显示文字
				width: '2px', //条宽度
				height: '100px', //高度
				textPosition: 'bottom', //设置文本的垂直位置
				// fontOptions: “bold italic”,//使文字加粗体或变斜体
				// background: “#eee”,//设置条形码的背景
				// font: “fantasy”,//设置文本的字体
				margin: 15 //设置条形码周围的空白边距
			});
		}

vue3引入console

安装 vconsole

npm i vconsole -s

在main.js 中引用之后在移动端就可以使用了

//main.js
import Vconsole from 'vconsole';
let vConsole = new Vconsole();
export default vConsole

vue3引入axios

引入axios
在npm 中安装 axios
npm i axios -s
全局引入

//main.js
import Axios from 'axios'
const app = createApp(App)
app.config.globalProperties.$axios = Axios;

页面中使用:

this.$axios.get('CSIIDW/pweb-eCNY.getWalletInfo.do', {
					headers: {
						'Content-Type': 'application/x-www-form-urlencoded',
						Accept: 'application/json'
					},
					params
				})
				.then(res => {
					this.$toast.clear();
				})
				.catch(error => {
					console.log('error:', error);
				});

vue3引入swiper

在vant 组件库中有 swipe 组件,但是功能不够齐全,需要引入 专业的 swiper 组件,实现相应的功能。
经过很多的尝试之后发现 swiper 7 暂时还不够成熟,之前用的swiper 5也有很多的问题无法解决,最终选择了swiper 6 实现页面效果。大部分人都说swiper6很坑,但是项目实测没有什么问题
"swiper": "^6.3.5",
安装

npm i swiper@6.3.5

全局引入:

import App from './App.vue'
const app = createApp(App)
import VueAwesomeSwiper from 'vue-awesome-swiper' 

import 'swiper/swiper-bundle.css'
import { Swiper, SwiperSlide } from 'swiper/vue'; //导入模组
SwiperCore.use([Navigation, Pagination, Scrollbar, A11y]); //使用模组
app.use(VueAwesomeSwiper, /* { default options with global component } */) //全局注册插件

全局引入比较复杂,不入尝试一下单页面引入:

import Swiper from "swiper";
//这里是,下载了swiper的css文件,然后放到项目中进行引入
import "../../assets/swipe/swiper.min.css";
mounted() {
    const mySwiper = new Swiper(".swiper-container", {
      direction: "horizontal", // 垂直切换选项
      loop: false, // 循环模式选项
      //   centeredSlides: true,
      centeredSlidesBounds: true,
      slidesPerView: "auto",
      slidesOffsetBefore: 37.5,
      on: {
        slideChangeTransitionEnd: function () {
          if (this.realIndex == 0) {
            this.showSlide = true;
            document.getElementsByClassName("goUp")[0].style.opacity = "100";
            document.getElementsByClassName("goUp")[1].style.opacity = "100";
          } else {
            this.showSlide = false;
            document.getElementsByClassName("goUp")[0].style.opacity = "0";
            document.getElementsByClassName("goUp")[1].style.opacity = "0";
          }
        },
      },
    });
    console.log(mySwiper);
  },

页面中写入:

 <swiper ref="mySwiper" :options="swiperOptions" @swiper="onSwiper" @click="gg" 
          @slideChange="onSlideChange">
            <swiper-slide><img src="../assets/img/1.jpg" alt=""></swiper-slide>
            <swiper-slide><img src="../assets/img/2.jpg" alt=""></swiper-slide>
            <swiper-slide><img src="../assets/img/3.jpg" alt=""></swiper-slide>
        </swiper>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值