Vue3_12(h函数 | jsx)
h函数 全局 API | Vue.js https://v3.cn.vuejs.org/api/global-api.html#h
Vue在生成真实的DOM之前,会将我们的节点转换成VNode,而VNode组合在一起形成一颗树结构,就是虚拟DOM(VDOM)
h() 函数是一个用于创建 vnode 的一个函数。createVNode() 简化为 h() 函数
接受三个参数:
1、{String | Object | Function} :一个Html标签名,一个组件,一个异步组件,一个函数式组件【必需】
2、{Object} Props:与attribute、prop和事件相关的对象【可选填】
3、{String | Object | Array} children:子VNodes,使用h()创建或者使用字符串获取“文本VNode”、或有插槽的对象【可选填】
#App.vue
<script>
import { h } from "vue";
import HelloWorld from "./HelloWorld.vue";
export default {
//setup 方式
// setup() {
// return () => {
// ......
// };
// },
//render方式
render() {
return h("div", null, [
h(HelloWorld, null, {
default: (props) =>
h("span", null, `app传入到HelloWorld中的内容: ${props.name}`)
})
]);
},
};
</script>
#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: "coderwhy"}): h("span", null, "我是HelloWorld的插槽默认值")
])
}
}
</script>
jsx 渲染函数 | Vue.js https://v3.cn.vuejs.org/guide/render-function.html#jsx
jsx通常会通过Babel来进行转换(React编写的jsx就是通过babel转换的);
#安装
npm install @vue/babel-plugin-jsx -D
#babel.config.js
module.exports = {
presets: [
'@vue/cli-plugin-babel/preset'
],
plugins:[
'@vue/babel-plugin-jsx'
]
}
jsx组件使用
#App.vue
<script>
import HelloWorld from './HelloWorld.vue';
export default {
data() {
return {
counter: 0
}
},
render() {
const increment = () => this.counter++;
const decrement = () => this.counter--;
return (
<div>
<h2>当前计数: {this.counter}</h2>
<button onClick={increment}>+1</button>
<button onClick={decrement}>-1</button>
<HelloWorld>
</HelloWorld>
</div>
)
}
}
</script>
#HelloWorld.vue
<script>
export default {
render() {
return (
<div>
<h2>HelloWorld</h2>
{this.$slots.default ? this.$slots.default(): <span>哈哈哈</span>}
</div>
)
}
}
</script>

浙公网安备 33010602011771号