在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會報錯,目測是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)文章
Vue2響應(yīng)式系統(tǒng)之set和delete
這篇文章主要介紹了Vue2響應(yīng)式系統(tǒng)之set和delete,通過為對象收集依賴,將對象、數(shù)組的修改、刪除也變成響應(yīng)式的了,同時為用戶提供了和方法,下文詳細(xì)介紹需要的朋友可以參考一下2022-04-04關(guān)于nuxt?store中保存localstorage的問題
這篇文章主要介紹了關(guān)于nuxt?store中保存localstorage的問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10Vue.js實現(xiàn)一個SPA登錄頁面的過程【推薦】
本篇文章主要介紹了Vue.js寫一個SPA登錄頁面過程的相關(guān)知識,具有很好的參考價值。下面跟著小編一起來看下吧2017-04-04