Table of Contents
1. Interpolation
2. Class and style binding
3. Conditional rendering
4. List rendering
5. Event processing
6, v-model
7, slot Slot
8. Use tsx to implement recursive components-menu
Home Web Front-end Vue.js Let's talk about the elegant use of jsx/tsx in vue3

Let's talk about the elegant use of jsx/tsx in vue3

Oct 08, 2022 pm 06:07 PM
vue vue.js vue3

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!

Let's talk about the elegant use of jsx/tsx in vue3

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)

viteThe 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
Copy after login

After installation, insert the code in vite.config.ts

import vueJsx from "@vitejs/plugin-vue-jsx";

export default defineConfig({
  plugins: [
    vueJsx(),
  ]
})
Copy after login

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>
Copy after login

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>
Copy after login

Style binding requires the use of double curly braces

const color = 'red'
const element = <sapn>style</sapn>
Copy after login

3. Conditional rendering

  • Only the v-show instruction is retained in jsx/tsx, but there is no v-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>
   )
}
Copy after login

5. Event processing

  • The binding event also uses single curly brackets {}, but the event binding is not prefixed with @. Instead, it was changed to on. For example: the click event is onClick

  • 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 used Modifier

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>
    )
}
Copy after login

6, v-model

jsx/tsx supports v-model syntax

// 正常写法
<input> // vue
<input> // jsx

// 指定绑定值写法
<input> // vue
<input> // jsx

// 修饰符写法
<input> // vue
<input> // jsx
Copy after login

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>
        )
    }
})
Copy after login

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>
        )
    }
})
Copy after login

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

Lets talk about the elegant use of jsx/tsx in vue3

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 <div class="code" style="position:relative; padding:0px; margin:0px;"><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(() =&gt; {             return routes         })         const currentPath = computed(() =&gt; {             return useRoute().path         })         return () =&gt; (             &lt;el-scrollbar&gt;                 &lt;el-menu&gt;                     {                         isShowRoutes.value.map((route) =&gt; {                             return &lt;menuitem&gt;&lt;/menuitem&gt;                         })                     }                 &lt;/el-menu&gt;             &lt;/el-scrollbar&gt;         )     } })</pre><div class="contentsignin">Copy after login</div></div>rrree by yourself in

menuItem

(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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Vue.js vs. React: Project-Specific Considerations Vue.js vs. React: Project-Specific Considerations Apr 09, 2025 am 12:01 AM

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

How to use vue traversal How to use vue traversal Apr 07, 2025 pm 11:48 PM

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values ​​for each element; and the .map method can convert array elements into new arrays.

How to jump to the div of vue How to jump to the div of vue Apr 08, 2025 am 09:18 AM

There are two ways to jump div elements in Vue: use Vue Router and add router-link component. Add the @click event listener and call this.$router.push() method to jump.

How to jump a tag to vue How to jump a tag to vue Apr 08, 2025 am 09:24 AM

The methods to implement the jump of a tag in Vue include: using the a tag in the HTML template to specify the href attribute. Use the router-link component of Vue routing. Use this.$router.push() method in JavaScript. Parameters can be passed through the query parameter and routes are configured in the router options for dynamic jumps.

See all articles