在vue中寫jsx的幾種方式
版本
本文版本配置 vue: 2.7.2 vue-cli: ~4.5.18; 本文代碼github倉庫地址
render函數(shù)
render函數(shù)和vue中的template是互斥的,template最終是要編譯成virtual Dom的,而render函數(shù)可以更直接構(gòu)建virtual Dom; virtual Dom由樹狀的vnode構(gòu)成,h函數(shù)可以構(gòu)建vnode
vue templates are compiled into virtual DOM render functions. vue also provides APIs that allow us to skip the template compilation step and directly author render functions
If both render and template are present in a component, render will take higher priority.
如果render和template同時出現(xiàn),render會有更高的權(quán)限(vue2不太一樣,下面會說)。
這些在文檔中有更直接的說明vue3 render函數(shù)
jsx/tsx
jsx類似于h函數(shù),都是更直接使用javascript來構(gòu)建DOM,需要注意的是jsx語法需要去編譯處理,有的腳手架可能有預(yù)先配置,有的沒有。
在typescript下需要編寫tsx
使用jsx的幾種方式
使用js對象注冊component
When not using a build step, a Vue component can be >defined as a plain JavaScript object containing >Vue-specific options:
vue組件也可以直接使用普通的js對象來注冊
// 定義一個js文件,導(dǎo)出組件對象
// componentObject.js
export default {
data() {
return {
msg: 'hello'
}
},
created() {
setTimeout(() => {
this.msg = 'hello world'
}, 1000);
},
render() {
return <h1>{this.msg}</h1>
}
}<script>
import componentObject from './../components/componentObject.js'
export default {
components: {
jsxComponent
}
};
</script>使用.vue文件
這里如果template和render函數(shù)如果同時指定的話,會用template覆蓋掉render,顯然是template優(yōu)先級更高,跟文檔上的render優(yōu)先級更高不一樣
// sfcJsx.vue
<!-- <template>
<div>test</div>
</template> -->
<script>
export default {
data() {
return {
msg: 'i am sfc jsx'
}
},
created() {
setTimeout(() => {
this.msg = 'i am sfc jsxxxx'
}, 1000);
},
render() {
return <h1>{this.msg}</h1>
}
}
</script>vue2.7在.vue文件中結(jié)合compositionApi和jsx
目前在setup中return jsx會報(bào)錯,目測是loader沒有支持(有知道解決辦法的老師傅也可以告訴我一下..),只能在setup使用compositionApi再加上render函數(shù)里寫jsx
// sfcJsx.vue
<script>
import { ref } from 'vue';
export default {
setup() {
const count = ref(0);
setTimeout(() => {
count.value = 12
}, 1000);
return {
count
}
},
render(h) {
return (
<h1>{this.count ? <span>11</span>: <span>22</span>}</h1>
)
}
}
</script>到此這篇關(guān)于在vue中寫jsx的幾種方式的文章就介紹到這了,更多相關(guān)vue使用jsx 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue.js中NaiveUI組件文字漸變的實(shí)現(xiàn)
這篇文章主要介紹了Vue.js中NaiveUI組件文字漸變的實(shí)現(xiàn),文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-07-07
Vue程序化的事件監(jiān)聽器(實(shí)例方案詳解)
本文通過兩種方案給大家介紹了Vue程序化的事件監(jiān)聽器,每種方案通過實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2020-01-01
Vue 組件(component)教程之實(shí)現(xiàn)精美的日歷方法示例
組件是我們學(xué)習(xí)vue必須會的一部分,下面這篇文章主要給大家介紹了關(guān)于Vue 組件(component)教程之實(shí)現(xiàn)精美的日歷的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2018-01-01
Vue JS對URL網(wǎng)址進(jìn)行編碼解碼,轉(zhuǎn)換為對象方式
這篇文章主要介紹了Vue JS對URL網(wǎng)址進(jìn)行編碼解碼,轉(zhuǎn)換為對象方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03
Vue使用html2canvas和jspdf實(shí)現(xiàn)PDF文件導(dǎo)出
這篇文章主要為大家詳細(xì)介紹了Vue如何使用html2canvas和jspdf實(shí)現(xiàn)PDF文件導(dǎo)出功能并設(shè)置頁面大小及方向,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-01-01

