【问题标题】:using svg sprite with vue storybook使用 svg sprite 和 vue 故事书
【发布时间】:2018-09-19 01:03:33
【问题描述】:

我使用最新的Vue CLI 创建了一个应用程序。

我正在使用vue-storybook 来生成样式指南。

我在 assets 下有一个名为 icons.svg 的 SVG Sprite 文件,我想创建一个 Icon.vue 组件,它接受图标的名称并从 sprite 中显示它。

组件如下所示:

//currently the href is hardcoded for testing purposes, 
//later on it would be passed as a property
<template>
    <svg class="icon">
        <use xlink:href="../assets/icons.svg#icon-compliance"></use>
    </svg>
</template>

<script>
export default {
  name: "AqIcon"
};
</script>

<style scoped>
.icon {
  display: inline-block;
  width: 1rem;
  height: 1rem;
  fill: red;
}
</style>

我有一个简单的故事来展示它:

storiesOf("Icon", module).add("Icon", () => ({
  components: { AqIcon },
  template: "<AqIcon />"
}));

问题是浏览器尝试加载 http://localhost:6006/assets/icons.svg 却找不到它,我尝试了各种网址,但我似乎无法找出正确的网址。

另外,我怎样才能使它动态?

【问题讨论】:

    标签: svg vue.js storybook


    【解决方案1】:

    您可以使用require()。只要确保您没有参数化它的整个参数(我的意思是,将文件夹和扩展名保留为硬编码字符串)。

    在下面的示例中,WebPack 将加载 /assets 文件夹中的所有 .svg 文件(因为它们可能在运行时被请求)。

    <template>
        <svg class="icon">
            <use :xlink:href="src"></use>
        </svg>
    </template>
    
    <script>
    export default {
      name: "AqIcon",
      props: ['icon'],
      computed: {
        src() {
          return require('../assets/' + this.icon + '.svg')
        }
      }
    };
    </script>
    

    【讨论】:

    • 谢谢!请更新答案,使计算结果如下所示:const sprite = require("../../assets/icons.svg"); return sprite + #icon-${this.icon}; 然后我将其标记为 true
    【解决方案2】:

    通过使其成为自己的 Vue 组件,在您的标记中包含一个 SVG 精灵。就我而言,我将 SVG sprite 组件放在 App.vue 中。

    App.vue:

    <template>
      <div class="body">
          <YourOtherComponents />
          <SvgSprite />
      </div>
    </template>
    
    <script>
    import YourOtherComponents from './Components/YourOtherComponents.vue';
    import SvgSprite from './Components/SvgSprite.vue';
    
    export default {
      name: 'App',
      components: {
        YourOtherComponents,
        SvgSprite,
      },
    };
    </script>
    

    SvgSprite.vue:

    <template>
      <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="display: none;">
        <symbol id="arrow-left" viewBox="0 0 24 24">
          <polyline points="15 18 9 12 15 6"></polyline>
        </symbol>
        <symbol id="arrow-right" viewBox="0 0 24 24">
          <polyline points="9 18 15 12 9 6"></polyline>
        </symbol>
      </svg>
    </template>
    
    <script>
    export default {
      name: 'SvgSprite',
    };
    </script>
    

    这样您就可以像在项目的 index.html 文件中内联精灵一样制作 svgs。它只是更清洁。

    【讨论】:

      猜你喜欢
      • 2021-06-06
      • 2021-06-16
      • 2019-04-15
      • 2019-04-08
      • 2022-08-12
      • 2020-08-13
      • 1970-01-01
      • 2019-08-28
      • 2020-05-01
      相关资源
      最近更新 更多