I have a sample project at https://github.com/ericg-vue-questions/leaflet-test/tree/fetch-method (fetch-method branch)
The relevant code is in LeafletTest.vue and is
<template>
<img src="./TheCloud.svg" />
</template>
<script>
export default {
name: "Map",
data() {
this.loadSVGIcon();
return {}
},
methods: {
async loadSVGIcon() {
const response = await fetch( "./TheCloud.svg" );
const svgSrc = await response.text();
console.log( "loadSVGIcon", response );
console.log( "loadSVGIcon", svgSrc );
},
},
};
</script>
<style scoped>
</style>
As I understand it, because I can get the svg to display with the <img ... /> tag, I should be able to use a fetch request to obtain the svg source.
However, when I do this, the text I get back is:
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="/favicon.ico">
<title>leaflet-test</title>
<link href="/js/app.js" rel="preload" as="script"><link href="/js/chunk-vendors.js" rel="preload" as="script"></head>
<body>
<noscript>
<strong>We're sorry but leaflet-test doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
<script type="text/javascript" src="/js/chunk-vendors.js"></script><script type="text/javascript" src="/js/app.js"></script></body>
</html>
which is weird.
What am I doing wrong? What do I need to change so I can get the SVG source?
CodePudding user response:
In order for fetch( "./TheCloud.svg" )
to work, it should be static file, which is located in /public
folder in Vue CLI projects. Also relative URL paths may give problems, while absolute paths like fetch( "/TheCloud.svg" )
are unambiguous.
Otherwise it can be bundled and imported from /src
:
const svgSrc = await import("./TheCloud.svg");
or
import svgSrc from "./TheCloud.svg";
The actual content of imported non-JS files like images depends on project configuration.