Vue3认识h函数
Vue推荐在绝大数情况下使用模板来创建你的HTML,然后一些特殊的场景,你真的需要JavaScript的完全编程的能力,这个时
候你可以使用 渲染函数 ,它比模板更接近编译器;
前面我们讲解过VNode和VDOM的概念:
- Vue在生成真实的DOM之前,会将我们的节点转换成VNode,而VNode组合在一起形成一颗树结构,就是虚拟DOM
(VDOM);
- 事实上,我们之前编写的 template 中的HTML 最终也是使用渲染函数生成对应的VNode;
- 那么,如果你想充分的利用JavaScript的编程能力,我们可以自己来编写 createVNode 函数,生成对应的VNode;
那么我们应该怎么来做呢?使用 h()函数:
- h() 函数是一个用于创建 vnode 的一个函数;
- 其实更准备的命名是 createVNode() 函数,但是为了简便在Vue将之简化为 h() 函数;
h()函数 如何使用呢?
- h()函数 如何使用呢?它接受三个参数:
h("button", { onClick: increment }, "+1")
// button:标签名
// { onClick: increment } 标签里的属性
// "+1" 标签里的文本注意事项:
- 如果没有props,那么通常可以将children作为第二个参数传入;
- 如果会产生歧义,可以将null作为第二个参数传入,将children作为第三个参数传
h函数的基本使用
h函数可以在两个地方使用:
- render函数选项中;
- setup函数选项中(setup本身需要是一个函数类型,函数再返回h函数创建的VNode);
import { h } from 'vue'
export default {
render(){
return h('div',{class:"app"},"Hello App")
}
}h函数计数器案例
options-Api中
<script>
import { h } from 'vue';
export default{
data(){
return {
counter:0
}
},
render(){
return h("div",{className:"app"},[
h("h2",null,`当前计数:${this.counter}`),
h("button",{ onClick: this.increment},"+1"),
h("button",{ onClick: this.decrement},"-1"),
])
},
methods:{
increment(){
this.counter++
},
decrement(){
this.counter--
}
}
}
</script>setup函数中使用
<script>
import { h, ref } from 'vue'
export default {
setup() {
const counter = ref(0)
const increment = () => {
counter.value++
}
const decrement = () => {
counter.value--
}
return () => h("div", { className: "app" }, [
h("h2", null, `当前计数: ${counter.value}`),
h("button", { onClick: increment }, "+1"),
h("button", { onClick: decrement }, "-1"),
h(Home)
])
}
}
</script>Composition-Api 中
<template>
<render />
<h2>内容</h2>
</template>
<script setup>
import {ref,h} from 'vue';
import Home from "./Home.vue";
const counter = ref(0)
const increment = () =>{
counter.value++
}
const decrement = () =>{
counter.value--
}
const render = () => h("div",{className:"app"},[
h("h2",null,`当前计数:${counter.value}`),
h("button",{ onClick:increment },"+1"),
h("button",{onClick:decrement},"-1"),
h(Home) // 引入组件
])
</script>
注意:在setup中需要
实际开发中我们基本不用render函数,如果依然想使用JavaScript的方式渲染,我们一般用JSX来编写逻辑
感谢大家观看,我们下次见
It's not my first time to pay a visit this web page, i am visiting this website dailly and get good facts from here every day.
Hello, i think that i saw you visited my site so i got here to go back the want?.I'm trying to find things to improve my web site!I suppose its adequate to use a few of your concepts!!
Touche. Outstanding arguments. Keep up the great effort.
Wow, this post is good, my younger sister is analyzing these things, therefore I am going to let know her.
There's certainly a lot to learn about this topic. I like all the points you've made.
所有文章都令人印象深刻。由衷感谢 带来的灵感。
你 百分百 分享经验。坚持!
不常看到, 这么高质量的内容。谢谢。
@十二使徒岩 哪张图片?
照片令人惊艳。继续保持 心情。