clarkoy
clarkoy

Reputation: 410

VueJS pass custom property to child component via property value

I have a component named controls:

<li class="controls__item" v-if="options[0].save == 'show'"> 
   <button class="btn" :options[0].saveAttr>Save</button>
</li>

I'm having trouble rendering an attribute defined in the options property:

<controls :options='[{ save: "show", saveAttr: "sampleAttr='0' "}]'></controls>

This is what I'm trying to achieve:

<button class="btn" sampleAttr='0'>Save</button>

Upvotes: 1

Views: 1403

Answers (2)

thanksd
thanksd

Reputation: 55664

That's not the correct syntax for binding in Vue.

If the name of the attribute to bind to is never going to change, you should specify the name in the controls component:

<li class="controls__item" v-if="options[0].save == 'show'"> 
  <button class="btn" :sampleAttr="options[0].saveAttr">Save</button>
</li>

And just change the options to pass in a value for saveAttr:

<controls :options='[{ save: "show", saveAttr: "0" }]'></controls>

If the name of the attribute (or the number of attributes) could change, then you should pass an object to the v-bind directive like so:

<li class="controls__item" v-if="options[0].save == 'show'"> 
  <button class="btn" v-bind="options[0].saveAttrs">Save</button>
</li>

And then pass in an object for saveAttrs:

<controls :options='[{save : "show", saveAttrs: { sampleAttr: 0 }]'></controls>

Upvotes: 1

Frnak
Frnak

Reputation: 6812

Let's start with your testdata (just a little clean up) let's say you have two buttons since it seems like you want to do that later on. I'm not yet sure what the save : "show" is supposed to do - so I do my best to give a flexible example.

[{
   'text': 'Save',
   'click': function() {  alert('save'); }
,{
   'text': 'Delete',
   'click': function() {  alert('delete'); }
}]

Not lets say you have that testdata in your component called "controls"

<controls :options="[{'text': 'Save','click': function() {  alert('save'); },{'text': 'Delete','click': function() {  alert('delete'); }}]"> </controls>

As we can see your controls has an property called options. So your code for your component should look like:

<template>
    <div class="controls">

        <li class="controls__item" v-for="control in options"> 
          <button class="btn" @click="control.click">{{ control.text }}</button>
        </li>

    </div>
</template>

<script>
    export default {
        props: ['options']
    }
</script>

You need to define the prop you want to bind on the component (options). Options is now bound according to our test date. Since it's an array we can use v-for to loop through it. We then bind the given text as button content and the given click function as on click event.

I hope this helps.

Upvotes: 0

Related Questions