首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Vue动态xlink:href属性

Vue动态xlink:href属性
EN

Stack Overflow用户
提问于 2020-10-11 20:38:45
回答 1查看 555关注 0票数 0

我希望将图标名称作为道具传递给vue组件,并使用它来呈现依赖于该图标名称的图标。我通过将图标名称传递给组件并将xlink:href绑定到一个数据属性来调用href,但它不起作用!:/我该如何做?以下是组件代码:

代码语言:javascript
复制
<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>

下面是组件用法代码:

代码语言:javascript
复制
<Icon icon="down"/>
EN

回答 1

Stack Overflow用户

发布于 2020-10-11 22:29:13

它似乎工作得很好……

代码语言:javascript
复制
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()
    }
  }
})
代码语言:javascript
复制
<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>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64304102

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档