亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
JSX introduction
Using JSX in Vue3
安裝插件(@vitejs/plugin-vue-jsx)
新建 jsx 文件
語法
GitHub 源碼
Home Web Front-end Vue.js Detailed explanation of how to use JSX in Vue3+Vite

Detailed explanation of how to use JSX in Vue3+Vite

Dec 09, 2022 pm 08:27 PM
vue vue3 vite jsx

Vue How to use JSX in Vite? The following article will introduce to you how to use JSX in Vue3 Vite. I hope it will be helpful to you!

Detailed explanation of how to use JSX in Vue3+Vite

[Related recommendations: vuejs video tutorial, web front-end development

JSX introduction

JSX (JavaScript and XML), is an HTML-in-JavaScript syntax extension first introduced in React. JSX is a great way to describe how a UI should behave in the essence of how it should interact. JSX is an extension of JavaScript syntax, so HTML-like code can coexist with JS. For example:

const button = <MyButton color="blue" shadowSize={2}>
  Click Me
</MyButton>

The button constant is called a JSX expression. We can use this to render the <MyButton> tag in our application. Browsers cannot read and parse JSX directly. The JSX expression looks like this after being compiled (with tools like Babel or Parcel):

React.createElement(
  MyButton,
  {color: &#39;blue&#39;, shadowSize: 2},
  &#39;Click Me&#39;
)

In fact, JSX is just syntactic sugar for the React.createElement(component, props, ...children) function. You can skip the compilation step by writing the UI yourself using React.createElement(). However, doing so loses the declarative benefits of JSX and the code becomes harder to read. Compilation is an extra step in the development process, but many developers in the React community believe the readability of JSX is worth it. Additionally, popular tools make JSX-to-JavaScript compilation part of their setup process. You don't have to configure compilation yourself unless you want to. If you want to test what some specific JSX will be converted into JavaScript, you can try using the Online Babel compiler.

React does not require the use of JSX. Not using JSX in React is more convenient when you don't want to configure JSX compilation in the build environment. For example, code written in JSX:

class Hello extends React.Component {
  render() {
    return <div>Hello {this.props.toWhat}</div>;
  }
}

const root = ReactDOM.createRoot(document.getElementById(&#39;root&#39;));
root.render(<Hello toWhat="World" />);

can be written as code without JSX:

class Hello extends React.Component {
  render() {
    return React.createElement(&#39;div&#39;, null, `Hello ${this.props.toWhat}`);
  }
}

const root = ReactDOM.createRoot(document.getElementById(&#39;root&#39;));
root.render(React.createElement(Hello, {toWhat: &#39;World&#39;}, null));

Using JSX in Vue3

Vue uses The single-file component integrates the template, related scripts and CSS into a single file ending in .vue. These files are ultimately processed by JS packaging or build tools (e.g. Webpack, Vite). The

<template> element contains all the markup structure and component display logic. The template can contain any valid HTML, as well as Vue-specific syntax. By setting the lang attribute of the <template> tag, for example, you can use the Pug template by setting <template lang="pug"> Replaces standard HTML.

The <script> tag in the .vue file contains all non-display logic in the component and needs to export a JS object by default. This object is where components are registered locally, properties are defined, local state is handled, methods are defined, etc. During the build phase this object containing the template will be processed and converted into a Vue component with a render() function.

The CSS style of the component is written in the <style> tag. If the scoped attribute is added, Vue will limit the scope of the style to the content of the single-file component. inside. This is a solution similar to CSS-in-JS, but allows writing pure CSS. If you selected the CSS preprocessor when creating your project via the CLI, you can add the lang attribute to the <style> tag so that Webpack can process the content at build time.

Although jsx was first introduced by React, JSX syntax does not actually define runtime semantics and can be compiled into various output forms. If you have used JSX syntax before, please note that Vue’s JSX compilation method is different from the JSX compilation method in React, so you cannot use React’s JSX compilation in Vue applications. Some notable differences from React JSX syntax include:

  • 可以使用 HTML attributes 比如 classfor 作為 props - 不需要使用 classNamehtmlFor。
  • 傳遞子元素給組件 (比如 slots) 的方式不同。

Vue 的類型定義也提供了 TSX 語法的類型推導支持。當使用 TSX 語法時,確保在 tsconfig.json 中配置了 "jsx": "preserve",這樣的 TypeScript 就能保證 Vue JSX 語法編譯過程中的完整性。

安裝插件(@vitejs/plugin-vue-jsx)

vite 官方提供了官方的插件來支持在 vue3 中使用 jsx/tsx,直接安裝就行。

npm i @vitejs/plugin-vue-jsx -D

安裝完之后在 vite.config.js 文件中的 plugins 字段中添加 jsx 支持:

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

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

這樣就可以在項目中使用 jsx/tsx 了。

新建 jsx 文件

在項目中新建 jsx 或 tsx 后綴的文件,語法和 js 文件類似,但是和 .vue 文件中的 <script> 標簽一樣需要默認導出一個 JS 對象。該對象是在本地注冊組件、定義屬性、處理本地狀態(tài)、定義方法等的地方。

import HelloWorld from &#39;./HelloWorld.vue&#39;
export default {
  setup() {
    return () => <HelloWorld msg="11" />;
  },
};

語法

1、插值。與 vue 模板語法中的插值一樣,但是雙大括號 {{}} 變?yōu)榱藛未罄ㄌ?{}。大括號內(nèi)支持任何有效的 JavaScript 表達式,比如:2 + 2,user.firstName,formatName(user) 等。

// 模板語法
<span>{{ a + b }}</span>

// jsx/tsx
<span>{ a + b }</span>

2、class 類名綁定。有兩種方式,使用模板字符串或者使用數(shù)組。

// 模板字符串
<div className={ `header ${ isBg ? &#39;headerBg&#39; : &#39;&#39; }` }>header</div>
// 數(shù)組
<div class={ [ &#39;header&#39;, isBg && &#39;headerBg&#39; ] } >header</div>

3、style 樣式綁定。需要使用雙大括號。

const color = &#39;red&#39;
const element = <sapn style={{ color, fontSize: &#39;16px&#39; }}>style</sapn>

4、條件渲染。由于 jsx 本身具有 js 語法,所以不再需要使用 v-if 指令,使用 if/else 和三元表達式都可以實現(xiàn)。但是支持 v-show 指令。

const element = (name) => {
  if (name) {
    return <h1>Hello, { name }</h1>
  } else {
    return <h1>Hello, Stranger</h1>
  }
}

const element = icon ? <span class="icon"></span> : null;
// 以上代碼等效于:
const element = icon && <span class="icon"></span>;

5、列表渲染。同樣,由于 jsx 本身具有 js 語法,所以不再需要使用 v-for 指令,使用 JS 數(shù)組的 map 方法即可。

const listData = [
   {name: &#39;Tom&#39;, age: 18},
   {name: &#39;Jim&#39;, age: 20},
   {name: &#39;Lucy&#39;, age: 16}
]
return () => (
   <div>
     <div class={&#39;box&#39;}>
       <span>姓名</span>
       <span>年齡</span>
     </div>
   {
   prop.listData.map(item => <div class={&#39;box&#39;}>
       <span>{item.name}</span>
       <span>{item.age}</span>
     </div>
     })
   </div>
)

6、標簽屬性綁定。也是使用大括號包裹,不能使用 v-bind 指令。而 vue 組件中通過 <div v-bind="properties"></div> 批量綁定標簽屬性,在 JSX 中需要使用 <div {...properties}></div>。

const href = &#39;https://cn.vuejs.org/&#39;
const element = <a href={href}>Vue3</a>

7、事件綁定。使用的也是 單大括號 {},不過事件綁定不是以 @為前綴了,而是改成了 on,與原生相同。例如:click 事件是 onClick 或 onclick。

const confirm = () => {
  // 確認提交
}
<button onClick={confirm}>確定</button>

如果要帶參數(shù),需要使用箭頭函數(shù)進行包裹:

const confirm = (name) => {
  // 確認提交
}
<button onClick={() => confirm(&#39;Are you sure&#39;)}>確定</button>

8、事件修飾符。需要使用 withModifiers 方法,接收兩個參數(shù),第一個參數(shù)是綁定的事件,第二個參數(shù)是需要使用的事件修飾符。

import { withModifiers, defineComponent, ref } from &#39;vue&#39;

const App = defineComponent({
  setup() {
    const count = ref(0);

    const inc = () => {
      count.value++;
    };

    return () => (
      <div onClick={ withModifiers(inc, [&#39;self&#39;]) }>{ count.value }</div>
    );
  },
})
export default App

注意:Vue 模板中 ref 變量是可以直接解構(gòu)的,但是在 jsx 中不行,需要添加 .value,比如上面的 { count.value }。

9、v-model 雙向綁定。需要使用單大括號 {}。如果綁定屬性則需要一個數(shù)組,第一個元素為綁定的值,第二個元素為綁定的屬性。

// 綁定值
<input v-model="show" /> // vue
<input v-model={show.value} /> // jsx

// 綁定屬性
<input v-model:prop="show" /> // vue
<input v-model={[show.value,&#39;prop&#39;]} /> // jsx

// 修飾符寫法
<input v-model:prop.trim="show" /> // vue
<input v-model={[show.value,&#39;prop&#39;,[&#39;trim&#39;]]} /> // jsx

10、slot 插槽。jsx/tsx 中無法使用 slot 標簽,定義插槽方式一:通過 setup 函數(shù)的第一個參數(shù) ctx 上下文對象的 slots 的屬性,setup 函數(shù)默認接收兩個參數(shù):

  • props - 組件傳入的參數(shù)對象。
  • ctx - 上下文對象,上下文對象暴露了其他一些在 setup 中可能會用到的值,包括:
    • attrs - 透傳的 Attributes(非響應式的對象,等價于 $attrs)。
    • slots - 插槽(非響應式的對象,等價于 $slots)。
    • emit - 觸發(fā)事件的函數(shù)(等價于 $emit)。
    • expose - 暴露公共屬性的函數(shù)。

如果解構(gòu)了 props 對象,解構(gòu)出的變量將會丟失響應性,因此推薦通過 props.xxx 的形式來使用其中的 props。如果確實需要解構(gòu) props 對象,或者需要將某個 prop 傳到一個外部函數(shù)中并保持響應性,可以使用 toRefs()toRef() 這兩個工具函數(shù):

import { toRefs, toRef } from &#39;vue&#39;

export default {
  setup(props) {
    // 將 `props` 轉(zhuǎn)為一個其中全是 ref 的對象,然后解構(gòu)
    const { title } = toRefs(props)
    // `title` 是一個追蹤著 `props.title` 的 ref
    console.log(title.value)

    // 或者,將 `props` 的單個屬性轉(zhuǎn)為一個 ref
    const title = toRef(props, &#39;title&#39;)
  }
}

ctx 上下文對象是非響應式的,可以安全地解構(gòu):

export default {
  setup(props, { attrs, slots, emit, expose }) {
    ...
  }
}

attrs 和 slots 都是響應式(有狀態(tài))的對象,它們總是會隨著組件自身的更新而更新。這意味著你應當避免解構(gòu)它們,并始終通過 attrs.x 或 slots.x 的形式使用其中的屬性。此外,和 props 不同,attrs 和 slots 的屬性都不是響應式的。如果想要基于 attrs 或 slots 的改變來執(zhí)行副作用,那么應該在 onBeforeUpdate 生命周期鉤子中編寫相關邏輯。

expose 函數(shù)用于顯式地限制該組件暴露出的屬性,當父組件通過模板引用訪問該組件的實例時,將僅能訪問 expose 函數(shù)暴露出的內(nèi)容:

export default {
  setup(props, { expose }) {
    // 讓組件實例處于 “關閉狀態(tài)”
    // 即不向父組件暴露任何東西
    expose()

    const publicCount = ref(0)
    const privateCount = ref(0)
    // 有選擇地暴露局部狀態(tài)
    expose({ count: publicCount })
  }
}

通過 ctx 上下文對象的 slots 的屬性可以獲取插槽對象后,就可以定義插槽了。

import { defineComponent } from &#39;vue&#39;

export default defineComponent({
  setup(props, { slots }) { // 邏輯
    return () => {
      return <p>
     <button>{ slots.test?.() }</button>
     <button>{ slots.default?.() }</button>
     </p>
    }
  },
})

// 在引用的組件中
<template #test>slot-test</template>
<template #>slot-default</template>

定義插槽方式二:使用 renderSlot 函數(shù)。

import { renderSlot } from &#39;vue&#39;

<button>
  { renderSlot(slots, &#39;default&#39;) }
</button>

而如果在 jsx 中使用插槽,可以直接通過標簽屬性 slot,或通過 v-slots 指令。

import HelloWorld from &#39;./HelloWorld&#39;  
export default defineComponent({  
    setup() {  
        return () => (  
            <div class={&#39;box&#39;}>  
                <HelloWorld v-slots={{  
                    title: () => {  
                        return <p>我是title插槽</p>  
                    },  
                    default: () => {  
                        return <p>我是default插槽</p>  
                    }  
                }} />  
            </div>  
        )  
    }  
})

11、CSS Modules。引入局部樣式,相當于 vue 組件中 <style> 標簽的 scoped 屬性。

import styles from &#39;./index.module.scss&#39;

<div class={styles.wrap}></div>

GitHub 源碼

(學習視頻分享:vuejs入門教程編程基礎視頻

The above is the detailed content of Detailed explanation of how to use JSX in Vue3+Vite. 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

How to develop a complete Python Web application? How to develop a complete Python Web application? May 23, 2025 pm 10:39 PM

To develop a complete Python Web application, follow these steps: 1. Choose the appropriate framework, such as Django or Flask. 2. Integrate databases and use ORMs such as SQLAlchemy. 3. Design the front-end and use Vue or React. 4. Perform the test, use pytest or unittest. 5. Deploy applications, use Docker and platforms such as Heroku or AWS. Through these steps, powerful and efficient web applications can be built.

Laravel Vue.js single page application (SPA) tutorial Laravel Vue.js single page application (SPA) tutorial May 15, 2025 pm 09:54 PM

Single-page applications (SPAs) can be built using Laravel and Vue.js. 1) Define API routing and controller in Laravel to process data logic. 2) Create a componentized front-end in Vue.js to realize user interface and data interaction. 3) Configure CORS and use axios for data interaction. 4) Use VueRouter to implement routing management and improve user experience.

How to work and configuration of front-end routing (Vue Router, React Router)? How to work and configuration of front-end routing (Vue Router, React Router)? May 20, 2025 pm 07:18 PM

The core of the front-end routing system is to map URLs to components. VueRouter and ReactRouter realize refresh-free page switching by listening for URL changes and loading corresponding components. The configuration methods include: 1. Nested routing, allowing the nested child components in the parent component; 2. Dynamic routing, loading different components according to URL parameters; 3. Route guard, performing logic such as permission checks before and after route switching.

What is the significance of Vue's reactivity transform (experimental, then removed) and its goals? What is the significance of Vue's reactivity transform (experimental, then removed) and its goals? Jun 20, 2025 am 01:01 AM

ReactivitytransforminVue3aimedtosimplifyhandlingreactivedatabyautomaticallytrackingandmanagingreactivitywithoutrequiringmanualref()or.valueusage.Itsoughttoreduceboilerplateandimprovecodereadabilitybytreatingvariableslikeletandconstasautomaticallyreac

What are the core differences between Vue.js and React in componentized development? What are the core differences between Vue.js and React in componentized development? May 21, 2025 pm 08:39 PM

The core differences between Vue.js and React in component development are: 1) Vue.js uses template syntax and option API, while React uses JSX and functional components; 2) Vue.js uses responsive systems, React uses immutable data and virtual DOM; 3) Vue.js provides multiple life cycle hooks, while React uses more useEffect hooks.

How can internationalization (i18n) and localization (l10n) be implemented in a Vue application? How can internationalization (i18n) and localization (l10n) be implemented in a Vue application? Jun 20, 2025 am 01:00 AM

InternationalizationandlocalizationinVueappsareprimarilyhandledusingtheVueI18nplugin.1.Installvue-i18nvianpmoryarn.2.CreatelocaleJSONfiles(e.g.,en.json,es.json)fortranslationmessages.3.Setupthei18ninstanceinmain.jswithlocaleconfigurationandmessagefil

Vue responsive principle and solution to not trigger view updates when array updates? Vue responsive principle and solution to not trigger view updates when array updates? May 20, 2025 pm 06:54 PM

When Vue.js handles array updates, the view is not updated because Object.defineProperty cannot directly listen to array changes. Solutions include: 1. Use the Vue.set method to modify the array index; 2. Reassign the entire array; 3. Use the rewritten mutation method of Vue to operate the array.

How can you optimize the re-rendering of large lists or complex components in Vue? How can you optimize the re-rendering of large lists or complex components in Vue? Jun 07, 2025 am 12:14 AM

Methods to optimize the performance of large lists and complex components in Vue include: 1. Use the v-once directive to process static content to reduce unnecessary updates; 2. implement virtual scrolling and render only the content of the visual area, such as using the vue-virtual-scroller library; 3. Cache components through keep-alive or v-once to avoid duplicate mounts; 4. Use computed properties and listeners to optimize responsive logic to reduce the re-rendering range; 5. Follow best practices, such as using unique keys in v-for, avoiding inline functions in templates, and using performance analysis tools to locate bottlenecks. These strategies can effectively improve application fluency.

See all articles