Vue2 导出 SVG 元素作为文件下载

Sha*_*e G 2 javascript svg vue.js vue-component vuejs2

代码笔使用 pur javacript 将SVG作为文件下载。我想用Vue.js. 我有一个 svg,其中一个属性radius, 绑定到 vue 实例数据,并通过滑块动态控制。我希望能够随时通过单击按钮将当前的 svg 元素下载为 svg 文件。

模板,

<svg id="dynamicIllustration" version="1.1" baseProfile="full" width="300" height="200">
<rect width="100%" height="100%" fill="lightblue" />
<circle cx="150" cy="100" :r="radius" fill="lightgreen" />
<text x="150" y="125" font-size="60" text-anchor="middle" fill="gray">SVG</text>
</svg>
<button class="btn btn-primary btn-sm" @click="downloadSVG()">Download SVG</button>
<input style="display: inline-block;" type="range" min="0" max="100" width="100" class="form-control-range sliderSize" v-model="radius" id="formControlRange">
Run Code Online (Sandbox Code Playgroud)

我如何编写使用 vue 执行此操作的方法?

  downloadSVG(){
        console.log("running downloadSVG()");
        // document.querySelector(".link-download").addEventListener("click", (evt) => {
    const svgContent = document.getElementById("dynamicIllustration").outerHTML,
          blob = new Blob([svgContent], {
              type: "image/svg+xml"
          }),
          url = window.URL.createObjectURL(blob),
          link = evt.target;

    link.target = "_blank";
    link.download = "Illustration.svg";
    link.href = url;
// });

      },
Run Code Online (Sandbox Code Playgroud)

注释掉一行是因为点击事件已经被vue处理了。结果我没有evt,这就是当我尝试运行它时错误告诉我的。

谢谢,

Bou*_*him 5

Vue 会自动将事件传递给您的点击处理程序

  <a href="#" @click="downloadSVG" class="link-download btn btn-primary btn-sm">Download displayed SVG</a>
Run Code Online (Sandbox Code Playgroud)

你只需要像这样在你的方法中接收它:

    downloadSVG(evt){....
Run Code Online (Sandbox Code Playgroud)

  <a href="#" @click="downloadSVG" class="link-download btn btn-primary btn-sm">Download displayed SVG</a>
Run Code Online (Sandbox Code Playgroud)
    downloadSVG(evt){....
Run Code Online (Sandbox Code Playgroud)