简体   繁体   中英

Importing svg into vue3

I have the following component:

<template>
  <span class="iconDynamic" v-html="data.icon"></span>
</template>
<script lang="ts">
  import { defineComponent, ref } from "vue";
  import svgPlaceholder from '../icons/svg/placeholder.svg';
  import svgHelp from '../icons/svg/help.svg';

  export default defineComponent({
    name: 'DynamicIcon',
    setup() {
      const data = ref({
        icon: ""
      });
      return {
        data,
      };
    },
    mounted(): void {
      

There's code in mounted that sets data.icon = svgPlaceholder or svgHelp (later there will be more). I was expecting it to load the contents of the svg files. However, it renders as:

<span class="iconDynamic">/mySite.com/src/icons/svg/placeholder.svg</span>

I need these loaded inline so that they can be styled.

you want to set the src of an image with the path

<span class="iconDynamic">
    <img :src="data.icon" />
</span>

and just a quick note about

const data = ref({
    icon: ""
});

don't instanciate the value with en empty string, it will cause you typings problems later because svgPlaceholder is not a string, set it to null instead

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM