Complete Vue.js 2 Web Development_ Practical guide to building end-to-end web development solutions with Vue.js 2

(singke) #1
Advanced Vue.js - Directives, Plugins, and Render Functions Chapter 17

Using JSX to render a component


JSX is very popular in the React community. In Vue, you don't have to use JSX to build


templates for your components; you can use the much more familiar HTML. JSX, however,
is the next best thing you can do if you are forced to write a lot of render functions.


Getting ready


Before venturing into this recipe, you better play a little with the render function. The


previous recipes provide some exercises.


How to do it...


JSX needs a Babel plugin to work. For this recipe, I will assume that you are working within
the webpack template.


To install the babel plugin, you can run the following command:


npm install
babel-plugin-syntax-jsx
babel-plugin-transform-vue-jsx
babel-helper-vue-jsx-merge-props
--save-dev

Inside the .babelrc file, add the following in the plugins array:


"plugins": [
...
"transform-vue-jsx"
]

Run npm install, as usual, to actually install all the dependencies.


Now, open the main.js and delete everything inside. Replace it with the following code:


import Vue from 'vue'

/* eslint-disable no-new */
new Vue({
el: '#app',
render (h) {
return <div>{this.msg}</div>
},
data: {
Free download pdf