CodeOrc.com - Learn by example
X
Make an RPG
Vue Implementations

Example of Vue Render function

Vue's templating system works great for most things. But sometimes you need to be able to define a template programmatically.

Let's say you want to build a map tile area with 10 by 12 map tiles, and you wanted to alter their colors based on some logic in a function. That would be pretty challenging to do in a template.

First let's do a simple example:

Vue.component("tilemap", { render: function(createElement) { return createElement("h1") } });
DO IT

Now, let's create 3 elments within that top div element

Vue.component("tilemap", { render: function(createElement) { return createElement("div", {}, ["hi", " hi2", " hi3"]); } });
DO IT

Notice that 3rd argument, the array of "hi". We're going to construct that with a for loop now.

Vue.component("tilemap", { render: function( createElement ) { var arr = []; for( var x=0; x < 8; x++ ) { arr.push( " hi" + x ); } return createElement("div", {}, arr ); } });
DO IT

At this point, it becomes easy to add things programmatically. Each of the array elements can have a createElement function call. Now we can add color functions for the backgroundColor. Since we're doing it programmatically, we can get as fancy as we want with our function calls.

Vue.component("tilemap", { render: function( createElement ) { var arr = []; for( var i=0; i < 120; i++ ) { var str = decimalToHexString(i+20); var color = str + "0000"; var el = createElement("div", { style: { backgroundColor: "#" + color }, "class": { boxme: true } }); arr.push( el ); } return createElement("div", { "class": "container" }, arr ); } });
DO IT

The decimalToHexString function turns an integer into a color Hex. Then 120 div boxes get created, each one with a new color in it.

In the next lesson, we will learn about Example of How to Implement an item shop in Vue

Get the Latest Tutorial Updates
<< >>
X