1. Encapsulate SvgIcon components

SvgIcon. Vue file

<template>
  <div>
    <img v-if="svg" :src="svg" :class="$style.noSelect" height="24px" />
  </div>
</template>

<style module>
/* CSS Modules: */
.noSelect {
  user-select: none; /* Text cannot be selected, icon cannot be selected after setting */
}
</style>
<script>
export default {
  name: "SvgIcon".props: {
    iconName: String
  },
  data() {
    return {
      svg: null
    };
  },
  watch: {
    // Listen for icon. When icon changes, importIcon is called to import the currently passed SVG graph
    iconName(icon) {
      if (this.iconName) {
        this.importIcon(icon); }}},mounted() {
    if (this.iconName) {
      this.importIcon(this.iconName); }},methods: {
    importIcon(icon) {
      return import(/* webpackMode: "eager" */
      `.. /.. /public/icon/${icon}.svg`)
        .then(obj= > {
          console.log(obj);
          this.svg = obj.default;
        })
        .catch(e= > {
          this.svg = null;
          throwe; }); }}};</script>
Copy the code

Note the location of SVG:

Import and use the SvgIcon just encapsulated

<template>
  <div class="test-svgicon">
    <svg-icon :iconName="icon" ></svg-icon>
    <br />
    <el-button @click="changeIcon">Click change icon</el-button>
  </div>
</template>
<script>
import SvgIcon from "@/components/SvgIcon.vue";
export default {
  components: {
    SvgIcon
  },
  data() {
    return {
      icon: "users"
    };
  },
  methods: {
    changeIcon() {
      this.icon = "life"; }}};</script>
Copy the code

After clicking the button and changing the icon:

Iii. Attention:

  1. The SVG diagram must be a static resource in the public folder before it can be imported or required, otherwise the SVG will not be found.
  2. < img: SRC =”svgicon” Alt =”” height=”24px” /> The DOM is rendered in the form of an IMG tag, as shown in the figure below.

  3. Advantages of encapsulation: You don’t have to require that SVG individually everywhere, which reduces code and improves performance.
 <img :src="svgicon" alt="" height="24px" />
 <template>
  <div class="test-svgicon">
    <svg-icon :iconName="icon"></svg-icon>
    <br />
    <br />
    <img :src="svgicon" alt="" height="24px" />
    <br />
    <el-button @click="changeIcon">Click change icon</el-button>
  </div>
</template>
<script>
import SvgIcon from "@/components/SvgIcon.vue";
export default {
  components: {
    SvgIcon
  },
  data() {
    return {
      svgicon: require(".. /.. /.. /public/icon/users.svg"),
      icon: "users" // The value of icon here is the name of the icon, preferably in English
    };
  },
  methods: {
    changeIcon() {
      this.icon = "life"; }}};</script>
Copy the code