Mastering Vue JSX: Install, Write, and Optimize JSX in Vue 2
This guide explains how to install the Babel JSX plugin, write JSX inside Vue 2 components, covers key syntax differences, highlights important considerations, and suggests extensions like vue-class-component for more elegant component definitions.
Preface
When we normally write Vue components we usually use templates, which look concise and are recommended by the Vue author. However this approach has drawbacks such as difficult debugging and complex scenarios where templates are not simple or convenient.
1. Installation
Before using JSX we need to install the Babel plugin babel-plugin-transform-vue-jsx. After installation add the plugin configuration to .babelrc.
2. Writing JSX in Vue
Now we can happily write JSX inside Vue. In the example Test.vue the JSX is placed in the render method, which is supported only in Vue 2.0. Note that JSX syntax in Vue differs slightly from React.
The render method is compiled from the template, so components defined with templates and those defined with JSX end up the same. The compiled output looks like the following:
This means the two forms of components can reference each other.
3. Syntax
The code image below covers most Vue JSX syntax. DOM attributes need the domProps prefix, while class and style are special modules and do not need the prefix. Event listeners start with on or nativeOn.
4. Precautions
When mixing template components and JSX components, keep these points in mind:
Importing a JSX component into a template: register it via components and use kebab-case for props.
Importing a template component into JSX: convert kebab-case props to camelCase. Built‑in directives (except v-show) do not work in JSX; custom directives can be used with v-name={value} or v-name={{value, modifier: true}}. Native vnode data format can also be used for custom directives.
5. Extensions
If you find defining data, props, computed, and methods inside a Vue component not elegant, consider the vue-class-component plugin, which lets you write Vue components using ES6 classes and ES7 decorators.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Tencent IMWeb Frontend Team
IMWeb Frontend Community gathering frontend development enthusiasts. Follow us for refined live courses by top experts, cutting‑edge technical posts, and to sharpen your frontend skills.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
