Render function

Vue creates your HTML using a template. However, in special cases, this write dead mode can not meet the requirements, must need JS programming ability. At this point, you need render to create the HTML.

When is the render function appropriate

In an effort to encapsulate a set of generic button components at a time, buttons have four styles (Default success Error). First, you might think of the following implementation

  <div v-if="type === 'success'">success</div>
  <div v-else-if="type === 'error'">error</div>
  <div v-else-if="type === 'warm'">warm</div>
  <div v-else>default</div>
Copy the code

This is no problem when there are few button styles, but imagine that if there are more than ten button styles required, the text inside the button depends on the actual situation (such as the text inside the SUCCESS button may be OK, GOOD, etc.). The template dies in a very weak way. In cases like this, using the render function is optimal.

Rewrite button components as required

First of all, the render function generates the same content as template, so to use the render function, you need to remove the template tag from the.vue file. Keep only the logical layer.

export default {
  render(h) {
    return h('div', {'class': {
        btn: true.success: this.type === 'success'.error: this.type === 'error'.warm: this.type === 'warm'.default: this.type === 'default'
      },
      domProps: {
        innerHTML: this.$slots.default[0].text
      },
      on: {
        click: this.clickHandle
      }
    })
  },
  methods: {
    clickHandle() {
      // dosomething}},props: {
    type: {
      type: String.default: 'default'
    },
    text: {
      type: String.default: 'default'}}};Copy the code

According to componentized thinking, what can be abstracted is never written down logically. The clickHandle function here can trigger different logic depending on the type of the button, without further elaboration.

It is then called in the parent component

<btn
  v-for="(btn, index) in testData"
  :type="btn.type"
  :text="btn.text"
  :key="index">{{btn.text}}
</btn>
Copy the code

Use the JSX

Yes, it is too cumbersome to pass arguments in order to remember that each parameter is of the same type. This tedious process can be optimized with JSX.

return (
  <div
    class={{
      btn: true,
      success: this.type === 'success',
      error: this.type === 'error',
      warm: this.type === 'warm',
      default: this.type === 'default'
    }}
    onClick={this.clickHandle}>
    {this.$slots.default[0].text}
  </div>
)
Copy the code