Using JSX With Vue.js
Using JSX With Vue.js
Join the DZone community and get the full member experience.Join For Free
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!
You may also like: React.js vs. Vue.js: A Comparison of Popular Frameworks.
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.
Published at DZone with permission of Anthony Gore , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.