vue if conditional directive and other options

The vue if directive in vuejs can be used when making templates to create an element or not based on a condition.It can come in handy when working out a template, but there are other options as well when it comes to using render methods for example an actual javaScript if statement can be used. Never the less this will be q quick post on the vue if directive, and some alternative options as well in vuejs.

1 - Vue if basic example

So when working out a template the vue if directive can be used to define a condition that if true will result in the rendering of the element that it is used with, otherwise of false it will not render. the value that is used with the directive can be an expression or a data object property.

In this quick example if the type of a data object property is a number it will be fixed to two decimal points, else if it is a string then the full value of the number will be displayed. One element or another will be rendered, but not both depending on the type of the property.

So for this example I have a basic.js file that looks like this.

1
2
3
4
5
6
7
8
9
10
new Vue({
el: '#demo-if',
template: '<div>' +
'<p v-if=" typeof n === \'number\'" >{{ n.toFixed(2) }}</p>' +
'<p v-if=" typeof n === \'string\'" >{{ n }}</p>' +
'</div>',
data: {
n: Math.PI
}
});

And html that makes use of it that looks like this.

1
2
3
4
5
6
7
8
9
10
<html>
<head>
<title>vue if example</title>
<script src="/js/vuejs/2.6.10/vue.js"></script>
</head>
<body>
<div id="demo-if"></div>
<script src="basic.js"></script>
</body>
</html>

So then because the type of the data.n property is a number, the value of PI is fixed to two decimal points. A silly example but you get the idea, this directive can be used to set some conditions for the tendering of elements, and any children within them.

2 -Render methods as a vue if alternative

One alternative to the vue if directive is to get into using render methods in place of static templates. Within the body of a render method the full power of javaScript can be used including if statements and ternary operators.

1
2
3
4
5
6
7
8
9
new Vue({
el: '#demo-if',
render: function (createElement) {
return createElement('div',[createElement('p', typeof this.n === 'number' ? this.n.toFixed(2) : this.n)])
},
data: {
n: Math.PI
}
});

Directives like vue if can still be used in render methods as well, but why bother when you can just do anything that works with jvaScript when dealing with a render method.