search
HomeWeb Front-endJS TutorialBasic usage of render function in Vue (detailed tutorial)

Basic usage of render function in Vue (detailed tutorial)

Jun 08, 2018 pm 04:03 PM
render functionvue

This article mainly introduces how to use the render function in Vue. Now I will share it with you and give you a reference.

render function

vue creates your HTML through template. However, in special cases, this hard-coded model cannot meet the needs, and js programming capabilities must be required. At this point, you need to use render to create HTML.

When is it appropriate to use the render function?

In the process of encapsulating a set of common button components at one time, the button has four styles (default success error). First of all, you may think of the following implementation

 <p v-if="type === &#39;success&#39;">success</p>
 <p v-else-if="type === &#39;error&#39;">error</p>
 <p v-else-if="type === &#39;warm&#39;">warm</p>
 <p v-else>default</p>

There is no problem at all when there are few button styles, but just imagine, if there are more than ten button styles required, the text in the button will be determined according to the actual situation ( For example, the text in the success button may be OK, GOOD, etc.). Then the hard-coded template method seems very weak. In situations like this, using the render function can be said to be the best choice.

Rewrite the button component according to the actual situation

First of all, the content generated by the render function is equivalent to the content of the template. Therefore, when using the render function, you need to first put it in the .vue file. Remove the template tag. Only the logical layer remains.

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

According to component-based thinking, things that can be abstracted are never hard-coded in logic. The clickHandle function here can trigger different logic according to the type of the button, so I won’t go into details.

Then call the parent component

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

Use jsx

Yes, remember the type of each parameter and the same usage, and pass the parameters in order It's really too much trouble. Then you can actually use jsx to optimize this tedious process.

return (
 <p
  class={{
   btn: true,
   success: this.type === &#39;success&#39;,
   error: this.type === &#39;error&#39;,
   warm: this.type === &#39;warm&#39;,
   default: this.type === &#39;default&#39;
  }}
  onClick={this.clickHandle}>
  {this.$slots.default[0].text}
 </p>
)

Example 2:

When you encounter writing similar components, you need to write a lot of long code, from the perspective of simplicity (laziness makes people progress) Therefore, we should find a more suitable method to achieve this effect.

 <body> 
    <p id="app"> 
      <mycomment :level="2"> 
        这是h2元素 
      </mycomment> 
    </p> 
  </body> 
  <script type="text/x-template" id="is"> 
 <p> 
  <h1 v-if="level === 1"> 
   <slot></slot> 
  </h1> 
  <h2 v-if="level === 2"> 
    <slot></slot> 
  </h2> 
  <h3 v-if="level === 3"> 
   <slot></slot> 
  </h3> 
  <h4 v-if="level === 4"> 
   <slot></slot> 
  </h4> 
  <h5 v-if="level === 5"> 
   <slot></slot> 
  </h5> 
  <h6 v-if="level === 6"> 
   <slot></slot> 
  </h6> 
 </p> 
</script> 
  <script> 
    Vue.component(&#39;mycomment&#39;,{ 
      template:&#39;#is&#39;, 
      props:{ 
        level:{ 
          type:Number, 
          required:true, 
        } 
      } 
    }) 
    var app =new Vue({ 
      el:&#39;#app&#39;, 
    }) 
   </script>

At this time, the Render function solves this problem very well. Let’s start with a simple example. It has a basic skeleton.

 <body> 
  <p id="app"> 
    <render-teample :level="4"> 
      render function 
 
    </render-teample> 
  </p> 
 
</body> 
<script> 
Vue.component(&#39;render-teample&#39;,{ 
  render:function(createElement){ 
    return createElement( 
      &#39;h&#39;+this.level, 
      this.$slots.default 
      ) 
  }, 
   props: { 
  level: { 
   type: Number, 
   required: true 
  } 
} 
  var app=new Vue({ 
    el:"#app", 
 
  }); 
 </script>

Then further add what you want to your component. The style requires events to become flesh and blood

 <body> 
    <p id="app"> 
      <render-teample :level="4" > 
 
        <p class="jah" slot="myslot">render function</p> 
      </render-teample> 
    </p> 
 
  </body> 
  <script> 
  Vue.component(&#39;render-teample&#39;,{ 
    render:function(createElement){ 
      return createElement( 
        &#39;h&#39;+this.level, 
        { 
          &#39;class&#39;:{ 
            show:true, 
            hide:false, 
          }, 
          style:{ 
            width:&#39;200px&#39;, 
            height:&#39;400px&#39;, 
            background:&#39;red&#39;, 
          }, 
          attrs:{ 
            name:&#39;h-ex&#39;, 
            id:&#39;h-id&#39; 
          }, 
          props:{ 
            myprops:true, 
          }, 
           on: { 
          click: function(event){ 
            alert(this.num) 
          } 
        }, 
          nativeOn:{ 
            click:function(event) { 
 
              alert(1111) 
            } 
          } 
 
        }, 
        [ 
          this.$slots.myslot, 
          createElement(&#39;p&#39;,{ 
             domProps:{ 
            innerHTML:&#39;holle render&#39; 
          } 
          }) 
        ] 
 
        ) 
    }, 
     props: { 
    level: { 
     type: Number, 
     required: true 
    } 
  } 
});  
    var app=new Vue({ 
      el:"#app", 
      data:{ 
        num:110 
      } 
    }); 
  </script>

Note: VNodes in the constraint component must be unique.

It is very painful to directly write all elements under one createElement() and is not conducive to maintenance.

So usually

var com1= createElement(&#39;p&#39;,&#39;item1&#39;);var
com2= createElement(&#39;p&#39;,&#39;item1&#39;);

You can use return createElement('p',[com1,com2])

This situation is prohibited return createElement('p', [com1,com1])

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to implement mysql transaction automatic recycling connection in Node.js

How to delete a certain object in a JS array Element

Details introduction to the knowledge points about promise in js

The above is the detailed content of Basic usage of render function in Vue (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.