Table of Contents
Background
Grammar
1. Ordinary content
2. Dynamic variables
# The function differences between
There are two types in vue3 ref, one refers to the two-way binding variable
in jsx When the
Use case:
You can use
can be implemented using
10.Instruction The modifier usage
, such as v-loading
Home Web Front-end Vue.js How to use jsx syntax in vue3

How to use jsx syntax in vue3

May 12, 2023 pm 12:46 PM
vue3 jsx

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

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

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

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

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

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

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

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

    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)
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    WWE 2K25: How To Unlock Everything In MyRise
    1 months ago By 尊渡假赌尊渡假赌尊渡假赌

    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)

    vue3+vite: How to solve the error when using require to dynamically import images in src vue3+vite: How to solve the error when using require to dynamically import images in src May 21, 2023 pm 03:16 PM

    vue3+vite:src uses require to dynamically import images and error reports and solutions. vue3+vite dynamically imports multiple images. If vue3 is using typescript development, require will introduce image errors. requireisnotdefined cannot be used like vue2 such as imgUrl:require(' .../assets/test.png') is imported because typescript does not support require, so import is used. Here is how to solve it: use awaitimport

    How to use tinymce in vue3 project How to use tinymce in vue3 project May 19, 2023 pm 08:40 PM

    tinymce is a fully functional rich text editor plug-in, but introducing tinymce into vue is not as smooth as other Vue rich text plug-ins. tinymce itself is not suitable for Vue, and @tinymce/tinymce-vue needs to be introduced, and It is a foreign rich text plug-in and has not passed the Chinese version. You need to download the translation package from its official website (you may need to bypass the firewall). 1. Install related dependencies npminstalltinymce-Snpminstall@tinymce/tinymce-vue-S2. Download the Chinese package 3. Introduce the skin and Chinese package. Create a new tinymce folder in the project public folder and download the

    How Vue3 parses markdown and implements code highlighting How Vue3 parses markdown and implements code highlighting May 20, 2023 pm 04:16 PM

    Vue implements the blog front-end and needs to implement markdown parsing. If there is code, it needs to implement code highlighting. There are many markdown parsing libraries for Vue, such as markdown-it, vue-markdown-loader, marked, vue-markdown, etc. These libraries are all very similar. Marked is used here, and highlight.js is used as the code highlighting library. The specific implementation steps are as follows: 1. Install dependent libraries. Open the command window under the vue project and enter the following command npminstallmarked-save//marked to convert markdown into htmlnpmins

    How to refresh partial content of the page in Vue3 How to refresh partial content of the page in Vue3 May 26, 2023 pm 05:31 PM

    To achieve partial refresh of the page, we only need to implement the re-rendering of the local component (dom). In Vue, the easiest way to achieve this effect is to use the v-if directive. In Vue2, in addition to using the v-if instruction to re-render the local dom, we can also create a new blank component. When we need to refresh the local page, jump to this blank component page, and then jump back in the beforeRouteEnter guard in the blank component. original page. As shown in the figure below, how to click the refresh button in Vue3.X to reload the DOM within the red box and display the corresponding loading status. Since the guard in the component in the scriptsetup syntax in Vue3.X only has o

    How to select an avatar and crop it in Vue3 How to select an avatar and crop it in Vue3 May 29, 2023 am 10:22 AM

    The final effect is to install the VueCropper component yarnaddvue-cropper@next. The above installation value is for Vue3. If it is Vue2 or you want to use other methods to reference, please visit its official npm address: official tutorial. It is also very simple to reference and use it in a component. You only need to introduce the corresponding component and its style file. I do not reference it globally here, but only introduce import{userInfoByRequest}from'../js/api' in my component file. import{VueCropper}from'vue-cropper&

    How to use Vue3 reusable components How to use Vue3 reusable components May 20, 2023 pm 07:25 PM

    Preface Whether it is vue or react, when we encounter multiple repeated codes, we will think about how to reuse these codes instead of filling a file with a bunch of redundant codes. In fact, both vue and react can achieve reuse by extracting components, but if you encounter some small code fragments and you don’t want to extract another file, in comparison, react can be used in the same Declare the corresponding widget in the file, or implement it through renderfunction, such as: constDemo:FC=({msg})=>{returndemomsgis{msg}}constApp:FC=()=>{return(

    How to use defineCustomElement to define components in Vue3 How to use defineCustomElement to define components in Vue3 May 28, 2023 am 11:29 AM

    Using Vue to build custom elements WebComponents is a collective name for a set of web native APIs that allow developers to create reusable custom elements (customelements). The main benefit of custom elements is that they can be used with any framework, even without one. They are ideal when you are targeting end users who may be using a different front-end technology stack, or when you want to decouple the final application from the implementation details of the components it uses. Vue and WebComponents are complementary technologies, and Vue provides excellent support for using and creating custom elements. You can integrate custom elements into existing Vue applications, or use Vue to build

    How to use vue3+ts+axios+pinia to achieve senseless refresh How to use vue3+ts+axios+pinia to achieve senseless refresh May 25, 2023 pm 03:37 PM

    vue3+ts+axios+pinia realizes senseless refresh 1. First download aiXos and pinianpmipinia in the project--savenpminstallaxios--save2. Encapsulate axios request-----Download js-cookienpmiJS-cookie-s//Introduce aixosimporttype{AxiosRequestConfig ,AxiosResponse}from"axios";importaxiosfrom'axios';import{ElMess

    See all articles