How to use jsx/tsx elegantly in
vue? The following article will introduce to you the elegant use of jsx/tsx in vue3. I hope it will be helpful to you!
I believe that react
partners are all familiar with jsx/tsx
, now they are in vue3
You can also use the jsx/tsx
syntax. [Related recommendations: vuejs video tutorial]
Install the plug-in (@vitejs/plugin-vue-jsx)
vite
The official provides official plug-ins to support the use of jsx/tsx
in vue3
, just install it directly.
yarn add @vitejs/plugin-vue-jsx -D
After installation, insert the code in vite.config.ts
import vueJsx from "@vitejs/plugin-vue-jsx"; export default defineConfig({ plugins: [ vueJsx(), ] })
After configuration, you can use it in the projectjsx/tsx
La
1. Interpolation
The interpolation of jsx/tsx is the same as the interpolation in vue template syntax, and supports valid Javascript expressions, such as: a b
, a || 5
...
It’s just that in jsx/tsx, the double curly braces {{}}
have been changed to single curly braces {}
// vue3模板语法 <span>{{ a + b }}</span> // jsx/tsx <span>{ a + b }</span>
2. Class and style binding
There are two ways to bind class class name, using template string or using array.
- Use template strings to separate two class names with spaces
// 模板字符串 <div>header</div> //数组 <div>header</div>
Style binding requires the use of double curly braces
const color = 'red' const element = <sapn>style</sapn>
3. Conditional rendering
- Only the
v-show
instruction is retained in jsx/tsx, but there is nov-if
instruction - Using
if/else
and ternary expressions can be achieved
setup() { const isShow = false const element = () => { if (isShow) { return <span>我是if</span> } else { return <span>我是else</span> } } return () => ( <div> <span>我是v-show</span> { element() } { isShow ? <p>我是三目1</p> : <p>我是三目2</p> } <div> ) }<h2 id="strong-List-rendering-strong"><strong>4. List rendering</strong></h2> <p>Similarly, jsx/ There is no <code>v-for</code> instruction in tsx. To render the list, we only need to use the array method <code>map</code> of Js. </p> <pre class="brush:php;toolbar:false">setup() { const listData = [ {name: 'Tom', age: 18}, {name: 'Jim', age: 20}, {name: 'Lucy', age: 16} ] return () => ( <div> <div> <span>姓名</span> <span>年龄</span> </div> { prop.listData.map(item => { return <div> <span>{item.name}</span> <span>{item.age}</span> </div> }) } </div> ) }
5. Event processing
The binding event also uses single curly brackets
{}
, but the event binding is not prefixed with@
. Instead, it was changed toon
. For example: the click event isonClick
-
If you need to use event modifiers, you need to use
withModifiers
method,withModifiers
method receives two parameters, the first parameter is the bound event, and the second parameter is the event that needs to be usedModifier
setup() { const clickBox = val => { console.log(val) } return () => ( <div> clickBox('box1')}> <span>我是box1</span> <div> clickBox('box2')}> <span>我是box2</span> <div> clickBox('box3'), ['stop'])}>我是box3</div> </div> </div> ) }
6, v-model
jsx/tsx supports v-model syntax
// 正常写法 <input> // vue <input> // jsx // 指定绑定值写法 <input> // vue <input> // jsx // 修饰符写法 <input> // vue <input> // jsx
7, slot Slot
Define the slot
There is no slot
tag in jsx/tsx, you need to use to define the slot {}
Or use the renderSlot
function
setup function receives two parameters by default 1. props 2. ctx context which includes slots, attrs, emit, etc.
import { renderSlot } from "vue" export default defineComponent({ // 从ctx中解构出来 slots setup(props, { slots }) { return () => ( <div> { renderSlot(slots, 'default') } { slots.title?.() } </div> ) } })
Use slots
You can use slots through v-slots
import Vslot from './slotTem' export default defineComponent({ setup() { return () => ( <div> <vslot> { return <p>我是title插槽</p> }, default: () => { return <p>我是default插槽</p> } }} /> </vslot> </div> ) } })
8. Use tsx to implement recursive components-menu
The main function is to automatically generate a menu based on routing information
The effect is as follows
The code is as follows, if you need to control permissions or something , add the corresponding parameters in meta
of the routing information, and then control <pre class="brush:php;toolbar:false">// index.tsx
import { routes } from '@/router/index'
import MenuItem from './menuItem'
import './index.scss'
export default defineComponent({
setup() {
const isShowRoutes = computed(() => {
return routes
})
const currentPath = computed(() => {
return useRoute().path
})
return () => (
<el-scrollbar>
<el-menu>
{
isShowRoutes.value.map((route) => {
return <menuitem></menuitem>
})
}
</el-menu>
</el-scrollbar>
)
}
})</pre>rrree
by yourself in
(Learning video sharing: web front-end development, Basic Programming Video)
The above is the detailed content of Let's talk about the elegant use of jsx/tsx in vue3. For more information, please follow other related articles on the PHP Chinese website!

WhentheVue.jsVirtualDOMdetectsachange,itupdatestheVirtualDOM,diffsit,andappliesminimalchangestotherealDOM.ThisprocessensureshighperformancebyavoidingunnecessaryDOMmanipulations.

Vue.js' VirtualDOM is both a mirror of the real DOM, and not exactly. 1. Create and update: Vue.js creates a VirtualDOM tree based on component definitions, and updates VirtualDOM first when the state changes. 2. Differences and patching: Comparison of old and new VirtualDOMs through diff operations, and apply only the minimum changes to the real DOM. 3. Efficiency: VirtualDOM allows batch updates, reduces direct DOM operations, and optimizes the rendering process. VirtualDOM is a strategic tool for Vue.js to optimize UI updates.

Vue.js and React each have their own advantages in scalability and maintainability. 1) Vue.js is easy to use and is suitable for small projects. The Composition API improves the maintainability of large projects. 2) React is suitable for large and complex projects, with Hooks and virtual DOM improving performance and maintainability, but the learning curve is steeper.

The future trends and forecasts of Vue.js and React are: 1) Vue.js will be widely used in enterprise-level applications and have made breakthroughs in server-side rendering and static site generation; 2) React will innovate in server components and data acquisition, and further optimize the concurrency model.

Netflix's front-end technology stack is mainly based on React and Redux. 1.React is used to build high-performance single-page applications, and improves code reusability and maintenance through component development. 2. Redux is used for state management to ensure that state changes are predictable and traceable. 3. The toolchain includes Webpack, Babel, Jest and Enzyme to ensure code quality and performance. 4. Performance optimization is achieved through code segmentation, lazy loading and server-side rendering to improve user experience.

Vue.js is a progressive framework suitable for building highly interactive user interfaces. Its core functions include responsive systems, component development and routing management. 1) The responsive system realizes data monitoring through Object.defineProperty or Proxy, and automatically updates the interface. 2) Component development allows the interface to be split into reusable modules. 3) VueRouter supports single-page applications to improve user experience.

The main disadvantages of Vue.js include: 1. The ecosystem is relatively new, and third-party libraries and tools are not as rich as other frameworks; 2. The learning curve becomes steep in complex functions; 3. Community support and resources are not as extensive as React and Angular; 4. Performance problems may be encountered in large applications; 5. Version upgrades and compatibility challenges are greater.

Netflix uses React as its front-end framework. 1.React's component development and virtual DOM mechanism improve performance and development efficiency. 2. Use Webpack and Babel to optimize code construction and deployment. 3. Use code segmentation, server-side rendering and caching strategies for performance optimization.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Zend Studio 13.0.1
Powerful PHP integrated development environment

Notepad++7.3.1
Easy-to-use and free code editor
