學(xué)習(xí)這篇文章希望您已經(jīng)具備以下知識:
- vue.js的基本使用
- 對前端三件套(html遣妥、css擅编、js)已經(jīng)可以熟練使用了
文末有配套demo代碼
JSX是什么
JSX 是一種 Javascript 的語法擴(kuò)展,JSX = Javascript + XML,即在 Javascript 里面寫 XML爱态,因?yàn)?JSX 的這個特性谭贪,所以他即具備了 Javascript 的靈活性,同時又兼具 html 的語義化和直觀性锦担。(個人建議靈活度強(qiáng)的部分組件可以用JSX來代替俭识,整個項(xiàng)目JSX屬實(shí)沒必要)
XML學(xué)習(xí)地址(學(xué)與不學(xué)可隨意,了解就ok):https://www.w3school.com.cn/xml/index.asp
用template的弊端:https://www.mk2048.com/blog/blog_h1c2c22ihihaa.html
為什么要在 Vue 中使用 JSX
有時候洞渔,我們使用渲染函數(shù)(render function)來抽象組件套媚,渲染函數(shù)不是很清楚的參見官方文檔, 而渲染函數(shù)有時候?qū)懫饋硎欠浅M纯嗟模灾恍枰袀€了解磁椒。
渲染函數(shù):https://cn.vuejs.org/v2/guide/render-function.html#%E5%9F%BA%E7%A1%80
createElement(
'anchored-heading', {
props: {
level: 1
}
}, [
createElement('span', 'Hello'),
' world!'
]
)
其對應(yīng)的模板是下面:
<anchored-heading :level="1">
<span>Hello</span> world!
</anchored-heading>
你看這寫起來多費(fèi)勁堤瘤,這個時候就派上 JSX 上場了。在 Vue 中使用 JSX浆熔,需要使用 Babel 插件本辐,它可以讓我們回到更接近于模板的語法上,接下來就讓我們一起開始在 Vue 中寫 JSX 吧医增。
創(chuàng)建項(xiàng)目并配置Babel
vue create vue-jsx
# 選擇vue2的
安裝依賴:
npm install @vue/babel-preset-jsx @vue/babel-helper-vue-jsx-merge-props
# or
yarn add @vue/babel-preset-jsx @vue/babel-helper-vue-jsx-merge-props
配置 .babelrc(babel.config.js) :
module.exports = {
presets: [
'@vue/cli-plugin-babel/preset',
['@vue/babel-preset-jsx',
{
'injectH': false
}]
]
}
配置后我們啟動項(xiàng)目:
yarn serve
demo結(jié)構(gòu)圖:
配置了babel.config.js后慎皱,我們把App.vue引入的HelloWorld.vue改為HelloWorld.js,并且刪除HelloWorld.js中關(guān)于template和style,以及script標(biāo)簽调窍。
export default {
name: 'HelloWorld',
props: {
msg: String
}
}
JSX基礎(chǔ)用法
這里展示在 Vue 中書寫一些基礎(chǔ)內(nèi)容宝冕。
純文本张遭、動態(tài)內(nèi)容邓萨、標(biāo)簽使用、自定義組件菊卷、樣式和class
import myComponent from './myComponent'
import './HelloWorld.css'
// 創(chuàng)建一個組件button
const ButtonCounter = {
name: "button-counter",
props: ["count"],
methods: {
onClick() {
this.$emit("change", this.count + 1);
}
},
render() {
return (
<button onClick={this.onClick}>數(shù)量 {this.count}+</button>
);
}
};
export default {
name: 'HelloWorld',
components: {
myComponent
},
data () {
return {
text:'hello 紙沒了飛機(jī)',
inputText:'我吃了',
count: 0
}
},
props: {
msg: String
},
watch: {},
methods: {
onChange(val) {
this.count = val;
alert(this.count)
}
},
render() {
// const {text,inputText,count} = this //通過解構(gòu)缔恳,下方return片段中就不需要this
return (
<div>
<h3>內(nèi)容</h3>
{/* 純文本 */}
<p>hello, I am Gopal</p>
{/* 動態(tài)內(nèi)容 */}
<p>{ this.text }</p>
<p>hello { this.msg }</p>
{/* 輸入框 */}
<input/>
{/* 自定義組件 */}
<myComponent/>
<ButtonCounter
style={{ marginTop: "10px" }}
count={this.count}
type="button"
onChange={this.onChange}
/>
</div>
);
}
}
題外話:創(chuàng)建組件那里大家可以多學(xué)學(xué)const 創(chuàng)建的ButtonCounter組件的那種方式。在React中也是經(jīng)常會這么創(chuàng)建的洁闰。
這么看的話和在template里寫沒有多大區(qū)別歉甚,標(biāo)簽該是啥還是啥沒有變化。那么這么一想的話扑眉,style呢纸泄,class呢?接下來就是style和class樣式的寫法(包括動態(tài)樣式)
我們先給h3綁定一個class為colorRed:
<h3 class="colorRed">內(nèi)容</h3>
審查元素發(fā)現(xiàn)直接寫class綁定是可以的:
那么class的樣式怎么寫呢腰素?畢竟js文件里寫<style></style>貌似是不行的聘裁!
1、全局樣式
App.vue
<style>
.colorRed{
color: red;
}
</style>
2弓千、引入一個css文件或者配合style-loader引入一個less衡便、sass、stylus文件
注意:都需要安裝配置對應(yīng)的loader,既然都是JSX了镣陕,那我們用stylus來講解下谴餐,相信less、sass大家都會了呆抑。stylus是一個省略了{(lán)}岂嗓,靠縮緊來識別的css編譯器。(不想用stylus可跳過鹊碍,樣式這塊可隨意)
yarn add global stylus
yarn add --dev stylus stylus-loader
各種style安裝見:https://www.cnblogs.com/jimc/p/10265198.html
安裝完成后新建HelloWorld.styl摄闸,然后引入。
stylus的使用:http://www.reibang.com/p/5fb15984f22d
stylus官網(wǎng):https://stylus.zcopy.site/
控制臺stylus報錯見:https://blog.csdn.net/csdn_zhoushengnan/article/details/109448369
vscode編輯期報錯:安裝編輯器stylus語法插件妹萨,并重啟
在這里插入圖片描述
效果:
在這里插入圖片描述
行內(nèi)樣式style:
<p style="color:blue">hello, I am Gopal</p>
動態(tài)綁定class和style
<p style={this.isGreen?'color:green':''}>{ this.text }</p>
<p class={this.isYellow?'colorYellow':''}>hello { this.msg }</p>
<p style={this.isRed?colorRed:''}>紅色的文字</p>
屬性綁定和普通HTML一樣的
畢竟class和style可都是html的屬性年枕,這點(diǎn)相信大家都知道的。
<input placeholder="我是placeholder" />
<input placeholder={placeholderText} />
{/* 解構(gòu)N個屬性乎完,要啥放啥 */}
<div {...attrObj} />
效果:
常用指令
template常用指令:v-html | v-text熏兄、v-if、v-for树姨、v-modal等摩桶。template的指令在JSX是無法使用的,故需要一些寫法帽揪,請看下面硝清。
我新建個instructions.js用來示范指令這塊。在App.vue中引入转晰。
v-html | v-text
在 JSX 里面芦拿,如果要設(shè)置 dom 元素的 innerHTML,就用到 domProps查邢。
render() {
const { htmlCode } = this
return (
<div>
<div domPropsInnerHTML={htmlCode}></div>
</div>
);
}
雖然v-text有domPropsInnerText蔗崎,但沒有用的必要。
v-if
分簡單的和復(fù)雜的扰藕。
簡單:
render() {
let bool = false
return (
<div>
{ bool ? <button>按鈕1</button> : <button>按鈕2</button>}
</div>
);
}
復(fù)雜:
render() {
let num = 3
if(num === 1){ return( <button>按鈕1</button> ) }
if(num === 2){ return( <button>按鈕2</button> ) }
if(num === 3){ return( <button>按鈕3</button> ) }
}
v-for
就使用 map 方法來實(shí)現(xiàn)缓苛,在react中也是如此。
render(h) {
var list = [1,2,3]
return(
<div>
{ list.map(item => <button>按鈕{item}</button>) }
</div>
)
}
v-modal
注意:新版 vue-cli4 中邓深,已經(jīng)默認(rèn)集成了 JSX 語法對 v-model 的支持未桥,可以直接使用
<input v-model={this.value}>
如果你的項(xiàng)目比較老,也可以安裝插件 babel-plugin-jsx-v-model 來進(jìn)行支持
我可是cli4芥备,我來驗(yàn)證下:
驗(yàn)證結(jié)果:(通過)
當(dāng)然以上兩種方式你都不想搞冬耿,你也可以手動支持,這就涉及到監(jiān)聽事件了门躯,請向下看淆党。
監(jiān)聽事件及事件修飾符
監(jiān)聽事件想到用 onChange, onClick等。
需要注意的是,傳參數(shù)不能使用 onClick={this.removePhone(params)}染乌,這樣子會每次 render 的時候都會自動執(zhí)行一次方法
應(yīng)該使用 bind山孔,或者箭頭函數(shù)來傳參
methods: {
handleClick(val){
alert(val)
}
},
<button type="button" onClick={this.handleClick.bind(this, 11)}>點(diǎn)擊bind</button>
<button type="button" onClick={() => this.handleClick(11)}>點(diǎn)擊箭頭函數(shù)</button>
上面提到的用過監(jiān)聽事件來實(shí)現(xiàn)v-modal
<input type="text" value={this.text} onInput={this.input}/>
methods: {
input(e){
this.text = e.target.value
}
},
除此之外,還可以使用對象的方式去監(jiān)聽事件:
render() {
return (
<input
value={this.content}
on={{
focus: this.$_handleFocus,
input: this.$_handleInput
}}
nativeOn={{
click: this.$_handleClick
}}
></input>
)
}
其他事件的使用同理都是加on荷憋。
事件修飾符
和指令一樣台颠,除了個別的之外,大部分的事件修飾符都無法在JSX中使用勒庄,這時候你肯定已經(jīng)習(xí)慣了串前,肯定有替代方案的。
.stop : 阻止事件冒泡实蔽,在JSX中使用event.stopPropagation()來代替
.prevent:阻止默認(rèn)行為荡碾,在JSX中使用event.preventDefault() 來代替
.self:只當(dāng)事件是從偵聽器綁定的元素本身觸發(fā)時才觸發(fā)回調(diào),使用下面的條件判斷進(jìn)行代替
if (event.target !== event.currentTarget){
return
}
.enter與keyCode: 在特定鍵觸發(fā)時才觸發(fā)回調(diào)
if(event.keyCode === 13) {
// 執(zhí)行邏輯
}
除了上面這些修飾符之外局装,尤大大為了照顧我們這群CV仔坛吁,還是做了一點(diǎn)優(yōu)化的,對于.once,.capture,.passive,.capture.once,尤大大提供了前綴語法幫助我們簡化代碼
render() {
return (
<div
on={{
// 相當(dāng)于 :click.capture
'!click': this.$_handleClick,
// 相當(dāng)于 :input.once
'~input': this.$_handleInput,
// 相當(dāng)于 :mousedown.passive
'&mousedown': this.$_handleMouseDown,
// 相當(dāng)于 :mouseup.capture.once
'~!mouseup': this.$_handleMouseUp
}}
></div>
)
}
如果有參數(shù)傳遞給方法铐尚,不能直接(參數(shù))拨脉,會在頁面中立即觸發(fā),需要我在下面這種寫法:
clickOnce(val) {
alert(val);
},
<button
type="button"
on={{
'~click': ()=>this.clickOnce('只能點(diǎn)一次'),
}}
>
事件修飾符點(diǎn)擊一次
</button>
使用范圍(結(jié)合第三方ui組件)
不僅僅在 render 函數(shù)里面使用 JSX宣增,而且還可以在 methods 里面返回 JSX玫膀,然后在 render 函數(shù)里面調(diào)用這個方法。并且也可以直接使用例如elementui等ui組件爹脾。
JSX 還可以直接賦值給變量帖旨、例如使用elementui的el-dialog。(您在測試該案例時記得安裝elemnt)
methods: {
$_renderFooter() {
return (
<div>
<el-button>確定</el-button>
<el-button onClick={ () =>this.closeDialog() }>取消</el-button>
</div>
);
},
openDialog(){
this.visible = true
},
closeDialog(){
this.visible = false
}
},
render() {
const buttons = this.$_renderFooter();
return (
<div>
<Button onClick={ () =>this.openDialog() }>打開Dialog</Button>
<el-dialog visible={this.visible}>
<div>彈窗內(nèi)容</div>
<template slot="footer">{buttons}</template>
</el-dialog>
</div>
);
}
插槽
插槽就是子組件中提供給父組件使用的一個占位符誉简,插槽分為默認(rèn)插槽碉就,具名插槽和作用域插槽,下面我依次為您帶來每種在JSX中的用法與如何去定義插槽闷串。
默認(rèn)插槽
使用默認(rèn)插槽
使用element-ui的Dialog時,彈框內(nèi)容就使用了默認(rèn)插槽筋量,在JSX中使用默認(rèn)插槽的用法與普通插槽的用法基本是一致的烹吵,如下代碼所示:
render() {
return (
<ElDialog title="彈框標(biāo)題" visible={true}>
{/*這里就是默認(rèn)插槽*/}
<div>這里是彈框內(nèi)容</div>
</ElDialog>
)
}
自定義默認(rèn)插槽
在Vue的實(shí)例this上面有一個屬性slots.default就可以將默認(rèn)插槽加入到組件內(nèi)部桨武。
export default {
props: {
visible: {
type: Boolean,
default: false
}
},
render() {
return (
<div class="custom-dialog" vShow={this.visible}>
{/**通過this.$slots.default定義默認(rèn)插槽*/}
{this.$slots.default}
</div>
)
}
}
使用:
<myComponent visible={true} slot>我是自定義默認(rèn)插槽</myComponent>
另vShow相當(dāng)于 v-show肋拔,不代表別的也可以這樣!
具名插槽
使用具名插槽
有時候我們一個組件需要多個插槽呀酸,這時候就需要為每一個插槽起一個名字凉蜂,比如element-ui的彈框可以定義底部按鈕區(qū)的內(nèi)容,就是用了名字為footer的插槽。
render() {
return (
<ElDialog title="彈框標(biāo)題" visible={true}>
<div>這里是彈框內(nèi)容</div>
{/** 具名插槽 */}
<template slot="footer">
<ElButton>確定</ElButton>
<ElButton>取消</ElButton>
</template>
</ElDialog>
)
}
自定義具名插槽
在上節(jié)自定義默認(rèn)插槽時提到了slots.default茎杂,而對于具名插槽,可以使用this.$slots.footer進(jìn)行自定義纫雁。
render() {
return (
<div class="custom-dialog" vShow={this.visible}>
{this.$slots.default}
{/**自定義具名插槽*/}
<div class="custom-dialog__foolter">{this.$slots.footer}</div>
</div>
)
}
使用:
<myComponent visible={true}>
<template slot="footer">
<ElButton>確定</ElButton>
<ElButton>取消</ElButton>
</template>
</myComponent>
作用域插槽
使用作用域插槽
有時讓插槽內(nèi)容能夠訪問子組件中才有的數(shù)據(jù)是很有用的煌往,這時候就需要用到作用域插槽,在JSX中,因?yàn)闆]有v-slot指令轧邪,所以作用域插槽的使用方式就與模板代碼里面的方式有所不同了刽脖。比如在element-ui中,我們使用el-table的時候可以自定義表格單元格的內(nèi)容忌愚,這時候就需要用到作用域插槽曲管。
<myComponent1
visible={this.visible}
{...{
scopedSlots: {
test: ({ user }) => {
// 這個user就是子組件傳遞來的數(shù)據(jù),同理可這樣拿到el-table的row硕糊,不過test得是default翘地,不過案例還是我這樣
<div style="color:blue;">快來啊,{user.name}癌幕,看看這個作用域插槽</div>
},
},
}}
></myComponent1>
自定義作用域插槽
子組件中通過 {this.$scopedSlots.test({ user: {name:'紙飛機(jī)'}})} 指定插槽的名稱是 test衙耕,并將 user 傳遞給父組件。父組件在書寫子組件標(biāo)簽的時候勺远,通過 scopedSlots 值指定插入的位置是 test橙喘,并在回調(diào)函數(shù)獲取到子組件傳入的 user 值
注意:作用域插槽是寫在子組件標(biāo)簽中的,類似屬性胶逢。而不是像具名插槽放在標(biāo)簽內(nèi)部
新建個作用域插槽.js
// 一個為jsx的子組件(玩玩插槽)
export default {
name: "myComponent",
data() {
return {
};
},
props: {
visible: {
type: Boolean,
default: false,
},
listData: {
type: Array,
default: function() {
return [];
},
},
},
render() {
return (
<div vShow={this.visible}>
{/**自定義作用域插槽*/}
<div class="item">
{this.$scopedSlots.test({
user: {name:'紙飛機(jī)'}
})}
</div>
</div>
);
},
};
效果:
函數(shù)式組件
函數(shù)式組件是一個無狀態(tài)厅瞎、無實(shí)例的組件,詳見官網(wǎng)說明初坠,新建一個 FunctionalComponent.js 文件和簸,內(nèi)容如下:
// export default ({ props }) => <p>hello {props.message}</p>;
// 或者推薦下方寫法
export default {
functional: true,
name: "item",
render(h, context) {
console.log(context.props)
return <div style="color:red;font-size:18px;font-weight:bold">{context.props.message}</div>;
},
};
HelloWorld.js中使用:
<funComponent message="展示下函數(shù)式組件"></funComponent>
效果:
代碼地址
<b id="test1"> https://codechina.csdn.net/qq_32442973/vue2-jsx-demo.git</b>
后記
無論你是要用vue2的jsx還是vue3的jsx都沒有本質(zhì)區(qū)別,畢竟vue3是向下兼容vue2的碟刺;倘若你真的要學(xué)vue3的JSX锁保,我建議你學(xué)完vue2的再去學(xué);另我不推薦在vue中所有的組件和頁面都用JSX半沽,兩者需要權(quán)衡利弊爽柒;同時也不必?fù)?dān)心JSX和template的相互嵌套,兩者是可以互相嵌套的者填。
參考:
https://www.cnblogs.com/ainyi/p/13324222.html
https://www.jb51.net/article/205764.htm
https://cn.vuejs.org/v2/guide/render-function.html#%E4%BA%8B%E4%BB%B6-amp-%E6%8C%89%E9%94%AE%E4%BF%AE%E9%A5%B0%E7%AC%A6
https://www.cnblogs.com/htoooth/p/6973238.html
http://www.reibang.com/p/84b708c80598
https://cloud.tencent.com/developer/article/1704608