4

I currently have a component with this render function:

render(createElement, context) {

        return createElement(
            'div', {
                'class': 'sliced'
            },
            [
                createElement('div', {
                        'class' : 'sliced-inner',
                        'style' : context.style
                    }
                )

            ]
        )

    },

and I've added functional: true. The "style" is a computed value, but it doesn't seem to get passed with the context object. Is there any way to access computed values in a Vue render function?

2
  • Use this.style to access computed value in render function Commented Oct 24, 2017 at 12:09
  • I forgot to mention that I added "functional: true" to my component, which was needed to make the component reactive I believe. Since now, the content doesn't change when the computed value changes. Commented Oct 24, 2017 at 12:50

1 Answer 1

8

A functional component has no state, so a computed property is redundant. In the following example I'm creating a header component that toggles between foo and bar when clicked:

Vue.component('message', {
  render (createElement) {
    return createElement('h1', {
      on: {
        click: event => {
          return this.foo = !this.foo 
        }
      }
    }, this.fooBar)
  },
  computed: {
    fooBar() {
      return (this.foo) ? 'foo' : 'bar'
    }
  },
  data(){
    return {
      foo: true
    }
  }
});

As you can see the header value is based on a computed, and it works fine because it is not a functional component so can have state: https://jsfiddle.net/hwbbukvd/

If I make that a functional component by adding functional: true, then it does not work because it's display relies on the component having state: https://jsfiddle.net/cygjdjru/

See: https://v2.vuejs.org/v2/guide/render-function.html#Functional-Components

In your case, if you aren't looking for style to be reactive, then I'm guessing you just want to pass a prop

Vue.component('message', {
  functional: true,
  render(createElement, context) {
    return createElement('h1', context.props.foo)
  },
  props: {
    foo: {
      required: true
    }
  }
});

See: https://jsfiddle.net/qhzh0a2c/

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! That clarifies a lot :)

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.