JavaScript文件中使用JSX的方法步驟
在 Vue 項目中,你可以通過以下步驟在 .js 文件中使用 JSX:
1. 配置 Babel 支持 JSX
首先需要確保你的項目配置支持 JSX 轉(zhuǎn)換:
安裝必要依賴
npm install @vue/babel-plugin-jsx -D yarn add @vue/babel-plugin-jsx -D
配置 babel.config.js
module.exports = {
presets: [
'@vue/cli-plugin-babel/preset'
],
plugins: [
'@vue/babel-plugin-jsx'
]
}
2. 在 JS 文件中使用 JSX 的基本語法
// HelloWorld.js
import { defineComponent } from 'vue'
export default defineComponent({
name: 'HelloWorld',
props: {
msg: String
},
setup(props) {
return () => (
<div class="hello">
<h1>{props.msg}</h1>
<button onClick={() => console.log('clicked')}>Click me</button>
</div>
)
}
})
3. JSX 與模板語法的對比
模板語法 JSX 語法
<template> 標簽 直接在 JS 中寫 JSX
v-if {condition && <div/>}
v-for {items.map(item => <div key={item.id}>{item.name}</div>)}
v-bind 或 : 直接使用屬性 name={value}
v-on 或 @ onClick={handler}
v-model value={state} onChange={handler}
- 實際使用示例
帶狀態(tài)的組件
// Counter.js
import { defineComponent, ref } from 'vue'
export default defineComponent({
setup() {
const count = ref(0)
const increment = () => {
count.value++
}
return () => (
<div>
<p>Count: {count.value}</p>
<button onClick={increment}>Increment</button>
</div>
)
}
})
帶子組件的示例
// ParentComponent.js
import { defineComponent } from 'vue'
import ChildComponent from './ChildComponent'
export default defineComponent({
setup() {
const items = ['Apple', 'Banana', 'Orange']
return () => (
<div>
<h1>Fruit List</h1>
<ul>
{items.map(item => (
<ChildComponent item={item} key={item} />
))}
</ul>
</div>
)
}
})
- 注意事項
??文件擴展名??:雖然可以在 .js 文件中使用 JSX,但推薦使用 .jsx 擴展名以便區(qū)分
??Vue 指令??:在 JSX 中不能直接使用 Vue 指令,需要轉(zhuǎn)換為 JSX 等價形式
??樣式處理??:
// 使用對象語法
<div style={{ color: 'red', fontSize: '14px' }}></div>
// 使用 class
<div class={['foo', { active: isActive }]}></div>
??插槽??:
// 默認插槽
<Child>{() => '默認插槽內(nèi)容'}</Child>
// 具名插槽
<Child>
{{
default: () => '默認內(nèi)容',
header: () => <h1>標題</h1>
}}
</Child>
- 與 TypeScript 結(jié)合
如果你使用 TypeScript,可以創(chuàng)建 .tsx 文件:
// Hello.tsx
import { defineComponent, PropType } from 'vue'
interface User {
name: string
age: number
}
export default defineComponent({
props: {
user: {
type: Object as PropType<User>,
required: true
}
},
setup(props) {
return () => (
<div>
<p>Name: {props.user.name}</p>
<p>Age: {props.user.age}</p>
</div>
)
}
})
通過以上配置和示例,你就可以在 Vue 項目的 JavaScript 文件中自由使用 JSX 語法了。
或者不使用sertup
在 Vue 組件中直接使用 render 函數(shù)(不使用 setup)
在 Vue 中,你可以直接在組件選項中定義 render 函數(shù),而不需要使用 setup 函數(shù)。這種方式在 Vue 2 和 Vue 3 中都適用,是更傳統(tǒng)的寫法。
基本語法
import { h } from 'vue'
export default {
props: ['message'],
render() {
return h('div', this.message)
}
}
完整示例
- 簡單組件
// SimpleComponent.js
import { h } from 'vue'
export default {
name: 'SimpleComponent',
props: {
title: String,
count: Number
},
render() {
return h('div', [
h('h1', this.title),
h('p', `Count: ${this.count}`),
h('button', {
onClick: () => this.$emit('increment')
}, 'Add')
])
}
}
- 帶狀態(tài)的組件
// Counter.js
import { h } from 'vue'
export default {
data() {
return {
count: 0
}
},
methods: {
increment() {
this.count++
}
},
render() {
return h('div', [
h('p', `Current count: ${this.count}`),
h('button', {
onClick: this.increment
}, 'Increment')
])
}
}
JSX 版本
如果你配置了 JSX 支持(如前所述),可以這樣寫:
// JsxComponent.js
export default {
props: ['items'],
render() {
return (
<ul>
{this.items.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
)
}
}
與傳統(tǒng)模板的比較
模板語法 Render 函數(shù)等效
v-if="condition" condition ? h('div') : null
v-for="item in items" items.map(item => h('div', item))
v-bind:id="id" { id: this.id }
@click="handleClick" { onClick: this.handleClick }
v-model="value" 需要手動實現(xiàn)(見下方示例)
實現(xiàn) v-model
// InputComponent.js
import { h } from 'vue'
export default {
props: ['modelValue'],
emits: ['update:modelValue'],
render() {
return h('input', {
value: this.modelValue,
onInput: (e) => {
this.$emit('update:modelValue', e.target.value)
}
})
}
}
插槽處理
// LayoutComponent.js
import { h } from 'vue'
export default {
render() {
return h('div', [
h('header', this.$slots.header()),
h('main', this.$slots.default()),
h('footer', this.$slots.footer())
])
}
}
作用域插槽
// ScopedSlotComponent.js
import { h } from 'vue'
export default {
data() {
return {
user: {
name: 'John',
age: 30
}
}
},
render() {
return h('div', [
this.$slots.default({
user: this.user
})
])
}
}
到此這篇關(guān)于JavaScript文件中使用JSX的方法步驟的文章就介紹到這了,更多相關(guān)JavaScript使用JSX內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JavaScript雙問號操作符(??)的驚人用法總結(jié)大全
雙問號操作符是ES2020引入的一個用于處理變量默認值的新特性,與傳統(tǒng)的邏輯或操作符||不同,這篇文章主要介紹了JavaScript雙問號操作符(??)詳解及如何解決使用||時因類型轉(zhuǎn)換帶來的問題,需要的朋友可以參考下2025-04-04
SwfUpload在IE10上不出現(xiàn)上傳按鈕的解決方法
在測試中發(fā)現(xiàn)使用了SwfUpload實現(xiàn)的無刷新上傳功能,在IE10上竟然無法使用了,難道SwfUpload不支持嗎?下面與大家分享下通過修改SwfUplad.JS文件讓其支持ie102013-06-06
用JavaScrpt實現(xiàn)文件夾簡單輕松加密的實現(xiàn)方法圖文
電腦里經(jīng)常會存儲著重要文件,這些文件需要進行加密,有許多方法來實現(xiàn)。但如果想對一個文件夾里的所有文件都進行加密,數(shù)量少還可以,要是數(shù)量多豈不是得把人累死?2008-09-09
淺談JavaScript函數(shù)參數(shù)的可修改性問題
這篇文章主要是對JavaScript函數(shù)參數(shù)的可修改性進行了詳細的介紹,需要的朋友可以過來參考下,希望對大家有所幫助2013-12-12
JavaScript之underscore_動力節(jié)點Java學院整理
JavaScript是函數(shù)式編程語言,支持高階函數(shù)和閉包。函數(shù)式編程非常強大,可以寫出非常簡潔的代碼。下面通過實例講解JavaScript之underscore的相關(guān)知識,一起看看吧2017-07-07

