Moshe
Moshe

Reputation: 6991

How to Pass Props to Class Using VueJS Render Function

The following code works:

export default {
    props: ['tag', 'type', 'size', 'color', 'direction'],
    render(createElement) {
        return createElement(
            this.tag || 'div',
            {
                attrs: { class: 'ui label'}
            },
            this.$slots.default
        );
    }
}

I can create the following html tag and it renders properly:

<label-x tag="a">Label X Text</label-x>

It renders as follows:

<a class="ui label">Label X Text</a>

Now let's add a property to that html tag as follows:

<label-x tag="a" size="large">Label X Text</label-x>

What I want to happen is for the word 'large' to be added to the rendered classes, as follows:

<a class="ui label large">Label X Text</a>

I can't figure out, though, how to make that happen. I tried the following, but I got an error:

export default {
    props: ['tag', 'type', 'size', 'color', 'direction'],
    render(createElement) {
        return createElement(
            this.tag || 'div',
            {
                class: { this.size },
                attrs: { class: 'ui label'}
            },
            this.$slots.default
        );
    }
}

What am I doing wrong -- and, more importantly, how can I do it right?

Thanks.

Upvotes: 4

Views: 5416

Answers (1)

Bert
Bert

Reputation: 82439

This should do it.

export default {
  props: ['tag', 'type', 'size', 'color', 'direction'],
  render(createElement) {
    // set the default classes
    let classes = ["ui", "label"]
    //check to see if we have a size arrtibute
    if (this.size)
      classes.push(this.size)
    
    return createElement(
      this.tag || 'div',
      {
        attrs: { class: classes.join(" ")}
      },
      this.$slots.default
    );
}

Example.

Though, the documentation shows a class property you can use just like you would if you bound to class:

export default {
  props: ['tag', 'type', 'size', 'color', 'direction'],
  render(createElement) {
    let classes = ["ui", "label"]
    if (this.size)
      classes.push(this.size)

    return createElement(
      this.tag || 'div',
      {
        class: classes
      },
      this.$slots.default
    );
  }

Example.

Upvotes: 7

Related Questions