我在https://github.com/ericg-vue-questions/leaflet-test/tree/fetch-method上有一个示例项目(fetch方法分支)
相关代码在LeafletTest中。
<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>
我理解它,因为我可以让svg显示& lt; img……/比;标记,我应该能够使用获取请求来获取svg源代码。
然而,当我这样做时,我得到的文本是:
<!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>
很奇怪
我做错了什么?我需要做什么更改才能获得SVG源代码?
为了使fetch( "./TheCloud.svg" )
工作,它应该是静态文件,位于Vue CLI项目的/public
文件夹中。也相对URL路径可能给问题,而像fetch( "/TheCloud.svg" )
绝对路径是明确的。
否则可以从/src
捆绑导入:
const svgSrc = await import("./TheCloud.svg");
或
import svgSrc from "./TheCloud.svg";
导入的非js文件(如图像)的实际内容取决于项目配置。