Moshe
Moshe

Reputation: 7007

Can I use a Render Function inside a .vue File

I am looking to dynamically set the html tags for components. For instance:

  components: {
    test: {
      props: ['tag', 'attributes'],
      render(createElement) {
        return createElement(this.tag || 'div', {attrs: this.attributes || {}}, this.$slots.default);
      }
    }
  }

I can then use code like this in an html file:

<test tag="a" :attributes="{href:'http://www.google.com'}">a tag content</test>
<test tag="p">p tag content</test>

Now, what I want to do is split up my components using something like Vue Loader. Basically, I want to split up my different components into different files and then import them using a main.js file.

I tried something like this, but it doesn't work:

// components/test.js 
export default {
  components: {
    test: {
      props: ['tag', 'attributes'],
      render(createElement) {
        return createElement(this.tag || 'div', {attrs: this.attributes || {}}, this.$slots.default);
      }
    }
  }
}

// main.js
import Vue from 'vue'  // don't think this is relevant, but it's there
import Test from './components/Test.js'
new Vue({
    el: '#app',
    components: {
        Test
    }
})

This does NOT work thought.

Any idea how to get it to work?

Thanks

Upvotes: 6

Views: 1310

Answers (1)

Bert
Bert

Reputation: 82489

Structure test.js like this:

export default {
      props: ['tag', 'attributes'],
      render(createElement) {
        return createElement(this.tag || 'div', {attrs: this.attributes || {}}, this.$slots.default);
      }
}

Upvotes: 4

Related Questions