Home Web Front-end JS Tutorial Basic 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 function vue

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

1

2

3

4

<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>

Copy after login

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

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;

  }

 }

};

Copy after login

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

1

2

3

4

5

6

<btn

 v-for="(btn, index) in testData"

 :type="btn.type"

 :text="btn.text"

 :key="index">{{btn.text}}

</btn>

Copy after login

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

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>

)

Copy after login

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

<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>

Copy after login

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

<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>

Copy after login

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

<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>

Copy after login

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

1

2

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

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

Copy after login

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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1226
24
How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

How to use vue traversal How to use vue traversal Apr 07, 2025 pm 11:48 PM

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values ​​for each element; and the .map method can convert array elements into new arrays.

React vs. Vue: Which Framework Does Netflix Use? React vs. Vue: Which Framework Does Netflix Use? Apr 14, 2025 am 12:19 AM

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

See all articles