Reputation: 222
In a current Vue3 project, I am using the Material Design Icons (SVGs) via @mdi/js and rendering them with James Coyle's 'vue-icon' icon component.
relevant parts of the script section:
import SvgIcon from '@jamescoyle/vue-icon'
import { mdiClockStart, mdiAlert } from '@mdi/js'
...and the template:
<svg-icon type="mdi" :path="mdiClockStart"></svg-icon>
This renders perfectly as expected.
BUT, if I want to render icons dynamically from within a loop over a related id value (always a number), I start to hit a snag. In the template I have:
<div v-for="state in states" :key="state.id">
<svg-icon type="mdi" :path="stations[state.id].icon"></svg-icon>
</div>
and in the code, I have defined the array in data:
data: () => ({
stations: [
{ icon: 'mdiClockStart', color: 'color: green' },
{ icon: 'mdiAlert', color: 'color: red' }
]
})
This looks all well and good, but the browser console keeps telling me:
15:56:15.232 vue.runtime.esm.js:6829 Error: attribute d: Expected number, "mdiAlert"
...as if it tried to insert the actual SVG markup into the path, instead of just the name of the icon as in the static example above.
If I output the contents of that array with double curly braces, I get the string value from that .icon node as expected. I thought it would just substitute the value into the :path prop, just like you can do with the :style prop. But no luck.
EDIT: I also tried using a function inside :path to pass the state id and return the mdi icon name, but that also failed.
Any tips or hints? Feels like I am close, but have run out of ideas.
Thanks in advance!
Upvotes: 0
Views: 487
Reputation: 7108
You defined your sations as an array so it expects an index which is a number. So if your state.id
isn't a number this wont work.
But if I look at your code, you don't seem to need the stations
object:
<div v-for="state in states" :key="state.id">
<svg-icon type="mdi" :path="state.id"></svg-icon>
</div>
If the id is some other string you can define stations
as an object and then your template syntax works again:
stations: {
id1: { icon: 'mdiClockStart', color: 'color: green' },
id2: { icon: 'mdiAlert', color: 'color: red' }
}
Upvotes: 0