vue3使用原生input上传图片

看了下elment-plus的上传组件,比较头疼,而且样式自定义起来不叫麻烦,干脆用原生的吧

一、样式图片

二、代码部分

<script setup lang="ts">
import { ref } from 'vue';

const fileInput = ref<any>(null); // 使用ref引用DOM元素
const imageUrl = ref("https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100"); // 存储图片预览的URL

const file = ref<any>(null)

// 处理文件上传
const handleFileUpload = () => {
  //这里可以执行文件上传的操作,axios等
  console.log(file.value);
};

//选择图片
const handleSelect = () => {
  fileInput.value.click()
}

//获取选择的图片信息
const handleImage = () => {
  file.value = fileInput.value.files[0]; // 获取文件信息

  if (!file) return;

  // 预览图片
  const reader = new FileReader();
  reader.onload = (e:any) => {
    imageUrl.value = e.target.result; // 更新图片预览的URL
  };
  reader.readAsDataURL(file.value); // 读取文件内容
}
</script>

<template>
  <div class="content">
    <div class="info">
      <img  :src="imageUrl" alt="">
      <div class="handle">
        <button @click="handleSelect">选择图片</button>
        <button @click="handleFileUpload">开始上传</button>
        <input ref="fileInput" type="file" @change="handleImage"  accept="image/*" style="display: none;">
      </div>
    </div>
  </div>
</template>

<style scoped>
.content {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
}
.info {
  width: 300px;
  height: 500px;
  margin-top: 30px;
}
img {
  width: 100px;
  height: 100px;
  border: 1px solid red;
  border-radius: 50%;
}
</style>

没什么太高的难度,就不详细介绍了,怎么用注释里都有,希望对你有帮助!

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值