If you want to create templates in your script files and you find Vue’s
render() function to be difficult to work with, JSX may be just what you need.
To demonstrate, here’s a render function without JSX:
And with JSX:
If nothing else, it’s much easier to read!
Note: this article was originally posted here on the Vue.js Developers blog on 2017/02/27
Why use JSX with Vue?
There are many ways to specify a template in Vue:
- Using an HTML file
- Using a
templateproperty in your instance/component constructor
<template>tags in single file components
- Using a render function.
If you go with option 4, you have to create your nodes in a very unfamiliar way i.e. using the
JSX allows you use a render function and still have the look and feel of HTML. Some people find this much easier. Others find it dirty to mix HTML in with their JS.
Have a look at this example and you can decide if you like it or not.
We’re now going to create a dead-simple app that displays a span with the text content “Show the message”. When you click the span it will trigger an alert.
Firstly, let’s use Vue in the normal way with separate JS and HTML files:
Incorporating a render function
The following code does exactly the same thing as the above code, the only difference is that rather than using a template we will use a render function to create our template:
The render function is a little hard to read, right? And that’s just for one span, imagine using it for a more complex component!
Let’s use JSX now:
(index.html same as above)
JSX is just for development and will be transpiled away long before runtime. So we only need to consider JSX in terms of how it benefits our development flow (or not).
To transpile your JSX you can use the
babel-plugin-transform-vue-jsx module which is a plugin for Babel and Webpack. Simply add it to your Webpack config:
Now, when you do a webpack build, your JSX will be transpiled into standard JS.
Take A Free Vue.js Introduction Course! Learn what Vue is, what kind of apps you can build with it, how it compares to React & Angular, and more in this 30-minute video introduction. Enroll for free!