Home > Web Front-end > Vue.js > body text

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

青灯夜游
Release: 2022-10-08 18:07:25
forward
2672 people have browsed it

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 data-id="heading-4"><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!

Related labels:
source:juejin.cn
Previous article:Vue computed properties and listeners and filters super detailed introduction Next article:Let’s talk about how to use the vite plug-in to automate the skeleton screen
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
Latest Articles by Author
Latest Issues
Related Topics
More>
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template