Vue动态链接:href属性



我想将图标名称作为道具传递给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"/>

它似乎运行得很好。。。

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>

最新更新