在vue3项目中发现img标签的src路径如果是本地磁盘的路径会导致图片加载不出来

<template>
<h1>图片</h1>
  <img src="E:\系统默认\桌面\bg.png" alt="" />
</template>

<script lang="ts">
import { defineComponent } from '@vue/runtime-core';

export default defineComponent({
  setup() {

  },
});
</script>

 显示了地址图片的url但却并不会加载出来,而在本地直接链接是可以打开这个图片的,并且控制台会报错Not allowed to load local resource,即使用a标签一样,这是出于安全性考虑,浏览器的权限不会直接访问到本地。所以这个问题无解,需要做些转化,比如

①将图片文件放置于项目的static目录中

②将图片放于云平台

 

因此当双向绑定时,这个路径也是无法生效的。

使用项目中的相对路径就不会存在这种问题

<template>
<h1>图片</h1>
  <img src="../../public/Img/1646903362.jpg" alt="" />
</template>

 当双向绑定img标签的src时可以使用相对路径或者本地的localhost链接(可以将Img目录存放在vue项目中的pubilc目录下,或者是public的同级目录,两者是等效的),

<template>
  <h3>图片</h3>
  <img :src="ImgUrl1" alt="" />
  <br>
  <img :src="ImgUrl2" alt="" />
</template>

<script lang="ts">
import { defineComponent, ref } from '@vue/runtime-core';

export default defineComponent({
  setup() {
    let ImgUrl1 = ref('../../public/Img/1646903362.jpg');
    let ImgUrl2 = ref('http://localhost:8082/Img/1646903362.jpg');
    return {
      ImgUrl1,
      ImgUrl2,
    };
  },
});
</script>
<style>
img{
    height: 50px;
    width: 50px;
}
</style>t

双向绑定时可支持动态渲染

<template>
  <h3>图片</h3>
  <img :src="ImgUrl1" alt="" />
  <br />
  <img :src="ImgUrl2" alt="" />
  <button @click="change">点我改变图片2</button>
</template>

<script lang="ts">
import { defineComponent, ref } from '@vue/runtime-core';

export default defineComponent({
  setup() {
    let ImgUrl1 = ref('../../public/Img/1646903362.jpg');
    let ImgUrl2 = ref('http://localhost:8082/Img/1646903362.jpg');
    return {
      ImgUrl1,
      ImgUrl2,
    };
  },
  methods: {
    change() {
      this.ImgUrl2 = '../../public/Img/贵州.png';
    },
  },
});
</script>
<style>
img {
  height: 50px;
  width: 50px;
}
</style>
t

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐