Vue3 高级语法(一)—— h函数、jsx
生活随笔
收集整理的這篇文章主要介紹了
Vue3 高级语法(一)—— h函数、jsx
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
一、認(rèn)識h函數(shù)
Vue推薦在絕大數(shù)情況下使用模板來創(chuàng)建你的HTML,然后一些特殊的場景,你真的需要JavaScript的完全編程的能力,這個時候你可以使用渲染函數(shù) ,它比模板更接近編譯器;
前面我們講解過VNode和VDOM的改變:
- Vue在生成真實的DOM之前,會將我們的節(jié)點轉(zhuǎn)換成VNode,而VNode組合在一起形成一顆樹結(jié)構(gòu),就是虛 擬DOM(VDOM);
- 事實上,我們之前編寫的 template 中的HTML 最終也是使用渲染函數(shù)生成對應(yīng)的VNode;
- 那么,如果你想充分的利用JavaScript的編程能力,我們可以自己來編寫 createVNode 函數(shù),生成對應(yīng)的VNode;
那么我們應(yīng)該怎么來做呢?使用 h()函數(shù):
- h() 函數(shù)是一個用于創(chuàng)建 vnode 的一個函數(shù);
- 其實更準(zhǔn)確的命名是 createVNode() 函數(shù),但是為了簡便在Vue將之簡化為 h() 函數(shù);
二、h()函數(shù) 如何使用呢?
h()函數(shù) 如何使用呢?它接受三個參數(shù):
注意事項:
- 如果沒有props,那么通常可以將children作為第二個參數(shù)傳入;
- 如果會產(chǎn)生歧義,可以將null作為第二個參數(shù)傳入,將children作為第三個參數(shù)傳入;
三、h函數(shù)的基本使用
h函數(shù)可以在兩個地方使用:
-
render函數(shù)選項中;
-
setup函數(shù)選項中(setup本身需要是一個函數(shù)類型,所有需要在箭頭函數(shù)中再返回h函數(shù)創(chuàng)建的VNode);
render函數(shù)實現(xiàn)計數(shù)器
<script> import {h} from "vue";export default {data() {return {counter: 0}},render() {return h('div', {class: 'app'}, [h('h2', null, `當(dāng)前計數(shù):${this.counter}`),h('button', {onClick: () => this.counter++}, '+1'),h('button', {onClick: () => this.counter--}, '-1')])} } </script><style scoped> </style>setup函數(shù)實現(xiàn)計數(shù)器
<script> import {h, ref} from "vue";export default {// data() {// return {// counter: 0// }// },setup() {const counter = ref(0)return () => {return h('div', {class: 'app'}, [h('h2', null, `當(dāng)前計數(shù):${counter.value}`),h('button', {onClick: () => counter.value++}, '+1'),h('button', {onClick: () => counter.value--}, '-1')])}} } </script><style scoped> </style>四、函數(shù)組件和插槽的使用
Home.vue:
HelloWorld.vue:
<script> import {h} from "vue";export default {render() {return h('div', null, [h('h2', null, 'Hello World!'),this.$slots.default ? this.$slots.default({name: 'zep'}) : h('span', null, '我是hellowrold插槽的默認(rèn)值')])} } </script><style scoped></style>五、jsx的babel配置
如果我們希望在項目中使用jsx,那么我們需要添加對jsx的支持:
- jsx我們通常會通過Babel來進(jìn)行轉(zhuǎn)換(React編寫的jsx就是通過babel轉(zhuǎn)換的);
- 對于Vue來說,我們只需要在Babel中配置對應(yīng)的插件即可;
注意:新版本的vue-cli中不需要進(jìn)行安裝和配置操作了!
安裝Babel支持Vue的jsx插件:
在babel.config.js配置文件中配置插件:
六、jsx計數(shù)器案例
<script> import {ref} from "vue";export default {setup() {const counter = ref(0)const increment = () => {counter.value++}const decrement = () => {counter.value--}return {counter,increment,decrement}},render() {return (<div><div>當(dāng)前計數(shù): {this.counter}</div><button onClick={this.increment}>+1</button><button onClick={this.decrement}>-1</button></div>)} } </script><style scoped> </style>七、jsx組件的使用
總結(jié)
以上是生活随笔為你收集整理的Vue3 高级语法(一)—— h函数、jsx的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: axis=0 与axis=1 的区分
- 下一篇: 二、搭建Apache服务器 模板引擎