Element-upload组件不使用action属性上传封装

新建 UploadFile组件

<template>
  <div class="ming-upload">
    <el-upload
               v-loading="loading"
               class="avatar-uploader"
               action="#"
               :show-file-list="false"
               :http-request="HttpRequest"
               >
      <img v-if="headimg" :src="headimg" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
  </div>
</template>

action中写入#或者/,最重要的一步就是添加http-request属性

http-request:覆盖默认的上传行为,可以自定义上传的实现

在父组件引入UploadFile组件

<template>
  <upload-file :headimg="userForm.headimg" />
</template>

<script setup>
  import UploadFile from '@/components/UploadFile'
</script>

编写HttpRequest方法

const HttpRequest = (data) => {
  loading.value = true
  
  // new 一个formdata 对象 将我们的参数和文件赋值进去
  const formdata = new FormData()
  formdata.append('file', data.file)
  formdata.append('type', 'img')
  
  // 这里我用的是 vuex 调用dispatch,也可以直接些Axios
  Store.dispatch('common/uploadFile', formdata).then(res => {
    if (+res.code === 200) {
      // 把请求结果给图片属性src赋值
      heading.value = res.data
    }
    loading.value = false
  }).catch(_ => {
    loading.value = true
  })
}

到这 你会发现 图片上传成功了,但是图片没有更换还是空白或者还是之前的图片,甚至还报了个错怎么回事呢?

Vue规则:组件不能修改props外部数据

Vue中的 props 是单向向下绑定的
即:每次父组件更新时,子组件中的所有 props 都会刷新为最新的值。
但是如果在子组件中修改 props ,Vue会向你发出一个警告。(无法通过修改子组件的props来更改父组件。)

于是我们得借助Vue的语法糖来帮我们实现更新父组件的值:.sync修饰符

.sync是一个语法糖。是父组件监听子组件更新某个props的请求的缩写语法。

具体操作如下:

  1. 在父组件的heading属性上加上.sync修饰符
<upload-file  :headimg.sync="userForm.headimg" />
  1. 在子组件拿到接口返回的数据后更新父组件的值
function updateHeading(img) {
  emit('update:headimg', img)
}

这样就完成了对el-upload组件的基本封装了。(在需要使用的页面直接引入即可。)

具体代码:

<template v-if="type==='avatar'">
<el-upload
           v-loading="loading"
           class="avatar-uploader"
           action="#"
           :show-file-list="false"
           :http-request="HttpRequest"
           >
  <img v-if="headimg" :src="headimg" class="avatar">
  <i v-else class="el-icon-plus avatar-uploader-icon" />
  </el-upload>
</template>

<script setup>
import { ref, computed } from 'vue'
import Store from '@/store'

const loading = ref(false)

const props = defineProps({
  headimg: {
    type: String,
    default: () => ''
  }
})

const emit = defineEmits(['updateHeading'])

const headimg = computed(() => {
  return props.headimg
})
const HttpRequest = (data) => {
  loading.value = true
  const formdata = new FormData()
  formdata.append('file', data.file)
  formdata.append('type', 'img')
  Store.dispatch('common/uploadFile', formdata).then(res => {
    if (+res.code === 200) {
      updateHeading(res.data.path)
    }
    loading.value = false
  }).catch(_ => {
    loading.value = true
  })
}

function updateHeading(img) {
  emit('update:headimg', img)
}

</script>
<template>
 ....
  <upload-file  :headimg.sync="userForm.headimg" />
 ....
</template>
  • 15
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,我可以回答你的问题。为了在ElementUI的Upload中使用七牛云储存图片,你需要进行以下步骤: 1. 首先,你需要在七牛云上创建一个存储空间,并获取到你的Access Key和Secret Key。 2. 然后,在你的Vue项目中安装七牛云的SDK,可以使用npm命令进行安装: ``` npm install qiniu-js --save ``` 3. 在你的Vue组件中,你需要引入ElementUI的Upload组件,并添加一个自定义的上方法。这个方法将会在文件上时被调用: ```javascript <template> <el-upload class="upload-demo" action="/upload" :before-upload="beforeUpload" :on-success="handleSuccess" :on-error="handleError" :headers="headers" :data="data" :file-list="fileList" multiple> <el-button size="small" type="primary">点击上</el-button> </el-upload> </template> <script> import { Upload } from 'element-ui'; import Qiniu from 'qiniu-js'; export default { components: { Upload }, data() { return { fileList: [], token: '', key: '', domain: 'http://xxx.xxx.xxx.xxx/', headers: { 'Authorization': '', 'x-qiniu-url': '' }, data: { token: '', key: '' } }; }, methods: { beforeUpload(file) { // 获取上凭证 let that = this; return new Promise((resolve, reject) => { axios.get('YOUR_UPLOAD_URL') .then(response => { that.token = response.data.token; that.key = response.data.key; that.headers.Authorization = `UpToken ${that.token}`; that.headers['x-qiniu-url'] = that.domain; that.data.token = that.token; that.data.key = that.key; resolve(); }) .catch(error => { reject(error); }) }); }, handleSuccess(response, file, fileList) { // 上成功回调 console.log(response); }, handleError(error, file, fileList) { // 上失败回调 console.log(error); } } } </script> ``` 在这段代码中,我们引入了ElementUI的Upload组件和七牛云的SDK,然后在data中定义了一些变量,包括上凭证、上文件的key、七牛的域名、请求头和请求参数等。在beforeUpload方法中,我们向你的服务器请求上凭证,在请求成功后将认证信息和请求参数赋值给data和headers变量。在handleSuccess和handleError方法中,我们可以处理上成功和上失败的情况。 4. 最后,你需要在你的服务器端实现上凭证的生成。可以使用七牛云的SDK,也可以使用其他语言的SDK,例如Java或Python。在服务器端生成上凭证后,将凭证和上文件的key返回给前端。 例如,在Node.js中,你可以使用qiniu-sdk: ```javascript const qiniu = require('qiniu'); const accessKey = 'YOUR_ACCESS_KEY'; const secretKey = 'YOUR_SECRET_KEY'; const bucket = 'YOUR_BUCKET_NAME'; const mac = new qiniu.auth.digest.Mac(accessKey, secretKey); const options = { scope: bucket, expires: 7200 }; const putPolicy = new qiniu.rs.PutPolicy(options); const uploadToken = putPolicy.uploadToken(mac); app.get('/uploadToken', (req, res) => { const key = req.query.filename; res.json({ token: uploadToken, key: key }); }); ``` 在这个例子中,我们使用qiniu-sdk生成上凭证,并在/uploadToken路由中返回凭证和上文件的key。 这样,你就可以在ElementUI的Upload中使用七牛云存储图片了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值