search
HomeWeb Front-endVue.jsHow to use jsx syntax in vue3

    Background

    vue3Promote the use of composition-api setup form in the project
    Cooperate withjsx hooksForm, separated by business, the logic is clearer and maintenance is more convenient.

    Grammar

    The following mainly achieves the same function by comparing the different syntaxes of jsx and template

    1. Ordinary content

    Ordinary content constants are written in the same way

    //jsx 写法
    setup() {
      return ()=><p type="email">hello</p>
    }
    
    //tempalte 写法
      <tempalte>
         <p type="email">hello</p>
      </template>

    2. Dynamic variables

    jsx Use curly braces to wrap variables without quotation marks, such as <div age="{age}">{age}</div>
    tempalte content is wrapped in double braces, attribute variables start with a colon Such as <div :age="age">{{age}}</div>

    ##{} is a universal usage of jsx, you can write in it

    JS expression, Loop logicOperation, etc.

    //jsx 写法
    setup() {
      let age = 1           
      return ()=><div age={age}>{age}</div> //没有" "包裹,统一都是{}
    }
    
    //tempalte 写法
      <tempalte>
         <div :age="age">{{age}}</div>
      </template>
    3. Function events

    1. Basic usage

    # The function differences between

    ##jsx

    and tempalte are as follows:

    • jsx

      Use on Camel case (first letter is capitalized), template uses @ dash form

    • jsx

      The method name needs to be wrapped with {}, tempalte is wrapped with " "

    • Use case 1:
    //jsx 写法
    setup() {
      const age= ref(0);
      let inc = ()=>{
          age.value++
       }
      return ()=> <div onClick={inc}>{age.value}</div>
    }
    
    //tempalte 写法
      <tempalte>
         <div @click="inc">{{age}}</div>
       </template>

    2. Parameter advancement

    jsx

    and tempalte are the same: No self Functions that define parameters do not need to end with () jsx
    When using functions with parameters , you need to use arrow functions Package: {()=>fn(args)}jsx
    needs to use withModifiers to implement .self,.stopThe effect of modifiers such as

    Use case 2:
    //jsx 写法
    import { withModifiers} from "vue";
    ...
    setup() {
      const age= ref(0);
      let inc = ()=>{
          age.value++
       }
      return ()=> (
      <> //根 路径必须有节点,或者用<>代表fragment空节点
        <div onClick={inc}>{age.value}</div>  //无自定义参数,不需要()
        <div onClick={()=>inc(&#39;test&#39;)}>{age.value}</div>  //有参数,需要()=>包裹
        //withModifiers包裹vue修饰符
        <div onClick={withModifiers(inc, ["stop"])}>{age.value}</div> //也可以再inc函数中使用e.stopPropagation()等
        <input onKeyup=={(ev) => {     //键盘事件enter事件 
            //逻辑部分也可以写入js
            if (ev.key === &#39;Enter&#39;) {
               inc ();
            }
         }}></input > 
      </>
     )
    }
    
    //tempalte 写法
      <tempalte>
         <div @click="inc"}>{{age}}</div>
         <div @click="inc(&#39;test&#39;)"}>{{age}}</div>
         <div @click.stop="inc"}>{{age}}</div>  //stop修饰符
         <input @keyup.enter="inc"}>{{age}}</input>  //键盘事件enter事件
      </template>

    Four, ref binding

    There are two types in vue3 ref, one refers to the two-way binding variable

    defined by

    ref(), and the other is the ref reference bound to the Dom tag ## for

    ref() two-way binding variable
    , jsx will not automatically handle the

    .value problem to template, you need to manually add value for the Dom tag The ref reference , jsx directly uses the
    ref(null) variable , there is no need to add .value, tempalte uses the character with the same name String##Use case:

    //jsx 写法
    setup() {
      const divRef=ref(null);
      const age= ref(0);  
      return ()=>
       (
         <div ref={divRef} > //Dom标签的ref引用
            <span>{age.value}</span>   //ref()双向绑定变量
         </div>
       ) 
    }
    
    //tempalte 写法
      <tempalte>
         <div ref=&#39;divRef&#39;>  //Dom标签的ref,使用同名字符串
            <span>{{age}}</span>   //ref()双向绑定变量,不需要.value
         </div>
      </template>

    五丶v-model syntax

    Use

    v-model or v-models

    in jsx When the

    v-model

    component instead of template has only one v-model

    , use the v-model syntax
    component When there are only

    multiple v-model, you can use v-model:xx syntax
    When there are multiple v-model

    , you can also use
    v- models

    syntax, you need to pass a two-dimensional array ( is no longer recommended in the new version)Use example:

    //jsx 写法
    setup() {
      const age= ref(0);  
      const gender =ref(&#39;&#39;)
      return ()=>
       (
         <tz-input v-model={age} />   
         <tz-input v-model:foo={age} />  //v-model带修饰,推荐(v-model:修饰符)
         <tz-input v-model={[age, "foo"]} />  //v-model带修饰 (新版不推荐)
    
         //多个v-model
         <tz-input    //推荐(v-model:修饰符)
           v-model:foo={age}
           v-model:bar={gender}
         />  
         <tz-input   
           v-models={[          //使用v-models,传递二维数组 (新版不推荐)          
             [age, "foo"], 
             [gender, "bar"],
             ]}
         />
       ) 
    }
    
    //tempalte 写法
      <tempalte>
         <tz-input v-model="age" />
         <tz-input v-model.foo="age" />  //v-model带修饰
         <tz-input 
           v-model.foo="age"     //多个v-model
           v-model.bar="gender"
         />
      </template>
    Sixth, v-slots syntax

    Use v-slots instead of v-slot (abbreviated #) in jsx

    Use case:

    //jsx 写法
    //方法一
    const App = {
      setup() {
        const slots = {
          default: () => <div>A</div>,     //默认插槽
          bar: () => <span>B</span>,       //具名插槽
        };
        return () => <A v-slots={slots} />;
      },
    };
    //方法二
    const App = {
      setup() {
        return () => (
          <>
            <A>
              {{
                default: () => <div>A</div>,   //此方法 默认default不能少
                bar: () => <span>B</span>,   //具名插槽
              }}
            </A>
            <B>{() => "foo"}</B>
          </>
        );
      },
    };
    
    //tempalte 写法
     <tempalte>
       <tempalte v-slot:bar>  //具名插槽,也叫 #bar
         <A />
       </template>
       <tempalte v-slot:default>
         <A />
       </template>
     </template>

    Seven, v-for syntax

    jsx

    You can use

    map loop

    in js to implement tempalte’s v-for logicUse case:

    //jsx 写法
    setup() {
      const arr= ref([{label:&#39;1&#39;},{label:&#39;2&#39;},{label:&#39;3&#39;}]);      
      return ()=>(   
         <>
         { arr.value.map(item=> <span key={item.label}>{item.label}</span> ) }
         </>
        ) 
    }
    
    //tempalte 写法
      <tempalte>
         <span v-for="item in arr" :key="item.label">{{item.label}}</span> 
      </template>
    八丶v-if syntax

    jsx

    can be implemented using

    if logic

    , ternary operation, &&, || etc. in jstempalte’s v-ifLogicUse example:

    //jsx 写法
    setup() {
      const show= ref(false);      
      return ()=>(   
         <>
         {show && <span>test vif</span>}      //使用&&运算    
         {!show && <span>test velse</span>}
         </>
        ) 
    }
    
    setup() {
      const show= ref(false);      
      return ()=>(   
         <>
          <span>{show.value ? &#39;test vif&#39; : &#39;test velse&#39;}</span>    //三目运算   
         </>
        ) 
    }
    
    setup() {
      const show= ref(false); 
      const vif=()=>{
         if(show) {
            return  <span>test vif</span> 
         }
         return  <span>test velse</span> 
      }   
      return ()=>(   
         <>
            vif()   //if条件函数
         </>
        ) 
    }
    
    //tempalte 写法
      <tempalte>
         <span v-if="show">test vif</span> 
         <span v-else>test velse</span> 
      </template>
    9丶v-show syntax

    Use example:

    //jsx 写法
    setup() {
      const show= ref(false);      
      return ()=>(   
         <>
          <span v-show={show.value}> test vshow</span>    //v-show
         </>
        ) 
    }
    
    //tempalte 写法
      <tempalte>
        <span v-show="show"> test vshow </span> 
      </template>

    10.Instruction The modifier usage

    directive uses

    underscore

    , such as v-loading

    use case:

    //jsx 写法
    setup() {
      const isLoading= ref(true);      
      return ()=>(   
         <>
          <span v-loading_fullscreen_lock={isLoading}> loading </span>    
         </>
        ) 
    }
    
    //tempalte 写法
      <tempalte>
        <span v-loading.fullscreen.lock="isLoading"> loading </span> 
      </template>

    The above is the detailed content of How to use jsx syntax in vue3. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    Understanding Vue.js: Primarily a Frontend FrameworkUnderstanding Vue.js: Primarily a Frontend FrameworkApr 17, 2025 am 12:20 AM

    Vue.js is a progressive JavaScript framework released by You Yuxi in 2014 to build a user interface. Its core advantages include: 1. Responsive data binding, automatic update view of data changes; 2. Component development, the UI can be split into independent and reusable components.

    Netflix's Frontend: Examples and Applications of React (or Vue)Netflix's Frontend: Examples and Applications of React (or Vue)Apr 16, 2025 am 12:08 AM

    Netflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.

    The Frontend Landscape: How Netflix Approached its ChoicesThe Frontend Landscape: How Netflix Approached its ChoicesApr 15, 2025 am 12:13 AM

    Netflix's choice in front-end technology mainly focuses on three aspects: performance optimization, scalability and user experience. 1. Performance optimization: Netflix chose React as the main framework and developed tools such as SpeedCurve and Boomerang to monitor and optimize the user experience. 2. Scalability: They adopt a micro front-end architecture, splitting applications into independent modules, improving development efficiency and system scalability. 3. User experience: Netflix uses the Material-UI component library to continuously optimize the interface through A/B testing and user feedback to ensure consistency and aesthetics.

    React vs. Vue: Which Framework Does Netflix Use?React vs. Vue: Which Framework Does Netflix Use?Apr 14, 2025 am 12:19 AM

    Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

    The Choice of Frameworks: What Drives Netflix's Decisions?The Choice of Frameworks: What Drives Netflix's Decisions?Apr 13, 2025 am 12:05 AM

    Netflix mainly considers performance, scalability, development efficiency, ecosystem, technical debt and maintenance costs in framework selection. 1. Performance and scalability: Java and SpringBoot are selected to efficiently process massive data and high concurrent requests. 2. Development efficiency and ecosystem: Use React to improve front-end development efficiency and utilize its rich ecosystem. 3. Technical debt and maintenance costs: Choose Node.js to build microservices to reduce maintenance costs and technical debt.

    React, Vue, and the Future of Netflix's FrontendReact, Vue, and the Future of Netflix's FrontendApr 12, 2025 am 12:12 AM

    Netflix mainly uses React as the front-end framework, supplemented by Vue for specific functions. 1) React's componentization and virtual DOM improve the performance and development efficiency of Netflix applications. 2) Vue is used in Netflix's internal tools and small projects, and its flexibility and ease of use are key.

    Vue.js in the Frontend: Real-World Applications and ExamplesVue.js in the Frontend: Real-World Applications and ExamplesApr 11, 2025 am 12:12 AM

    Vue.js is a progressive JavaScript framework suitable for building complex user interfaces. 1) Its core concepts include responsive data, componentization and virtual DOM. 2) In practical applications, it can be demonstrated by building Todo applications and integrating VueRouter. 3) When debugging, it is recommended to use VueDevtools and console.log. 4) Performance optimization can be achieved through v-if/v-show, list rendering optimization, asynchronous loading of components, etc.

    Vue.js and React: Understanding the Key DifferencesVue.js and React: Understanding the Key DifferencesApr 10, 2025 am 09:26 AM

    Vue.js is suitable for small to medium-sized projects, while React is more suitable for large and complex applications. 1. Vue.js' responsive system automatically updates the DOM through dependency tracking, making it easy to manage data changes. 2.React adopts a one-way data flow, and data flows from the parent component to the child component, providing a clear data flow and an easy-to-debug structure.

    See all articles

    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

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    1 months agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    1 months agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    1 months agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Chat Commands and How to Use Them
    1 months agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Safe Exam Browser

    Safe Exam Browser

    Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    MinGW - Minimalist GNU for Windows

    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.

    DVWA

    DVWA

    Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

    PhpStorm Mac version

    PhpStorm Mac version

    The latest (2018.2.1) professional PHP integrated development tool