【问题标题】:Vue dynamic xlink:href attrVue 动态 xlink:href attr
【发布时间】:2020-10-11 12:38:44
【问题描述】:

我想将图标名称作为道具传递给 vue 组件并使用它来呈现取决于该图标名称的图标。 我通过将图标名称传递给组件并将 xlink:href 绑定到数据属性调用 href 来做到这一点,但它不起作用! :/ 我怎样才能做到这一点? 这是组件代码:

<template>
  <svg class="icon">
      <use :xlink:href="href"></use>
  </svg>
</template>

<script>
export default {
  name: 'Icon',
  props: {
    icon: String
  },
  data: function () {
      return {
        href: `@sprite#icon-kb-${this.icon}`
      }
    }
}
</script>

这里是组件使用代码:

<Icon icon="down"/>

【问题讨论】:

  • 你确定@sprite#icon-kb-down${this.icon} 吗?
  • @MichalLevý 是的,兄弟我对此很确定
  • 真的吗?图标是@sprite#icon-kb-downdown ?
  • @MichalLevý 谢谢,我修复了它,但在这里并不重要......
  • 好的,那么“不起作用”到底是什么意思?它根本没有渲染,是渲染但不正确还是其他什么?

标签: javascript vue.js vue-component


【解决方案1】:

看起来效果还不错……

const icon = Vue.component('Icon', {
  props: {
    icon: String
  },
  data: function () {
      return {
        href: `#${this.icon}`
      }
    },
  template: `
  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
      <use :xlink:href="href"></use>
  </svg>
  `
})

const ap = new Vue({
  el: "#app",
  components: { icon },
  data() {
    return {
      icons: ['icon-8pt-star', 'icon-star']
    }
  },
  computed: {
    iconsInReverseOrder() {
      return this.icons.slice().reverse()
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <Icon v-for="(icon, index) in icons" :icon="icon" :key="icon+'1'"></Icon>
</div>

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <symbol id="icon-8pt-star" viewBox="0 0 95 95">
    <path class="cls-1" d="M83.59,63.91,97.5,50,83.59,36.09V16.41H63.91L50,2.5,36.09,16.41H16.41V36.09L2.5,50,16.41,63.91V83.59H36.09L50,97.5,63.91,83.59H83.59Z" transform="translate(-2.5 -2.5)"/>
  </symbol>

  <symbol id="icon-star" viewBox="0 0 95 95">
    <polygon points="47.5 0 62.18 31.27 95 36.29 71.25 60.63 76.86 95 47.5 78.77 18.14 95 23.75 60.63 0 36.29 32.82 31.27 47.5 0"/>
  </symbol>
</svg>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-17
    • 1970-01-01
    • 1970-01-01
    • 2017-04-12
    • 2019-03-05
    • 1970-01-01
    • 2019-06-16
    • 2019-04-23
    相关资源
    最近更新 更多