3

I'm experimenting with Vue.js (2.3). I'm comfortable with attribute binding manually e.g.

Vue.component('my-component', {
    props: ['info'],
    computed: {
        type: function() { return info.type },
        classList: function() { return this.info.attributes.classList },
        id: function() { return this.info.attributes.id }
    }
    template: '<component :is="type" :class="classList" :id="id">{{ info.text }}</component>'
})

where info =

{
    text: 'Some text',
    type: 'h2',
    attributes: {
        classList: 'a string',
        id: 'another-string'
    }
}

This would output the following:

<h2 class="a string" id="another-string">Some text</h2> 

But what if I want to bind all the attributes inside my attributes object, regardless of how many or what they are e.g. my info might look like this:

{
    text: 'Some text',
    type: 'td'
    attributes: {
        classList: 'a string',
        id: 'another-string',
        colspan: '3',
        rowspan: '2',
        title: 'A string',
        ...
    }
}

How can I bind all these attributes without having to list all the possible attributes that might crop up?

1
  • I should add I could modify the attributes property to be a list or object, whatever is easier. E.g. attributes: [{key:"id", value:"a-string"},...] Commented Jun 30, 2017 at 9:47

1 Answer 1

12

v-bind accepts an object as it's parameter and binds all the properties to their values.

template: '<component :is="type" v-bind="info.attributes"></component>'
Sign up to request clarification or add additional context in comments.

1 Comment

How did I miss that? Thanks very much, works as you would expect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.