在项目中循环渲染的img标签中的图片要显示,src需要加请求头token(正常情况下,后端直接返回src的url)

子组件authImg中写标签渲染

<template>
  <img ref="img"> </img>
</template>
<script>
export default {
  name: "authImg",
  props: {
    authSrc: {
      type: String,
      required: false,
      default: "",
    }
  },
  mounted () {
    let token = sessionStorage.getItem('token')
    Object.defineProperty(Image.prototype, 'authsrc', {
      writable: true,
      enumerable: true,
      configurable: true
    })
    let img = this.$refs.img
    let request = new XMLHttpRequest();
    request.responseType = 'blob';
    request.open('get', this.authSrc, true);
    request.setRequestHeader('token', token);
    request.onreadystatechange = e => {
      if (request.readyState == XMLHttpRequest.DONE && request.status == 200) {
        img.src = URL.createObjectURL(request.response);
        img.onload = () => {
          URL.revokeObjectURL(img.src);
        }
      }
    };
    request.send(null);
  }
}
</script>

父组件中:

<authImg :authSrc="baseurl + '/download.do?id='+ files.name + '&height=60'" alt=""></authImg>

这样,循环渲染中,就将token加入到src的请求中了

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐