Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically add attributes to elements in vue.js?

Tags:

vue.js

Given an items array of objects:

items: [{
 label: 'My Link',
 attrs: {
  href: '/route',
  target: '_blank',
  title: 'Some title',
 },
},{
 label: 'My Link 2',
 attrs: {
  href: '/route2',
  target: '_self',
  title: 'Some title 2',
 },
}];

My vue has a v-for that loops through a list of items:

<ul>
  <li v-for="item in items">
    <a ADD_ITEM_ATTRIBUTES_HERE>{{ item.label }}</a>
  </li>
</ul>

How can I loop through each item's attribute and dynamically add it to the anchor element where the Attribute name is the object key and the attribute value is its matching value?

I'm coming from jQuery world where this kind of manipulation is pretty straight forward, but I'm not sure how to modify the DOM in this case.

Most questions I find here have to do with checking if an element has a prop or meets a condition to set its value. I'm not trying to do that. In my case I don't know what the prop will be nor its value.

like image 483
gdaniel Avatar asked Mar 06 '23 07:03

gdaniel


1 Answers

Since you already have attributes in an object, you can directly pass it to v-bind; Also see bind an object of attributes example:

<a v-bind="item.attrs">{{ item.label }}</a>

This will result in keys in attrs object as attributes and values in attrs as corresponding values.

like image 92
Psidom Avatar answered Mar 16 '23 07:03

Psidom