# 1.render 基本使用
vue | <script> |
| import { h } from 'vue'; |
| |
| export default { |
| data() { |
| return { |
| counter: 0 |
| } |
| }, |
| render() { |
| return h("div", {class: "app"}, [ |
| h("h2", null, `当前计数: ${this.counter}`), |
| h("button", { |
| onClick: () => this.counter++ |
| }, "+1"), |
| h("button", { |
| onClick: () => this.counter-- |
| }, "-1"), |
| ]) |
| } |
| } |
| </script> |
| |
| <style scoped></style> |
参考结果:
# 2.setup 中使用 render
vue | <script> |
| import { h, ref } from "vue"; |
| |
| export default { |
| setup() { |
| const counter = ref(0); |
| |
| return () => { |
| return h("div", { id: "app" }, [ |
| h("h2", null, `当前计数${counter.value}`), |
| h("button", { onclick: () => counter.value++ }, `+1`), |
| h("button", { onclick: () => counter.value-- }, `-1`), |
| ]); |
| }; |
| }, |
| }; |
| </script> |
| |
| <style scoped></style> |
参考结果:这种写法与上面是一样的
# 3.render 组件与插槽
# App
vue | <script> |
| import { h } from "vue"; |
| import Home from "./Home.vue"; |
| |
| export default { |
| render() { |
| |
| return h(Home, null, { |
| default: (props) => |
| |
| h("span", null, `app传入到Home中的内容:${props.name}`), |
| }); |
| }, |
| }; |
| </script> |
| |
| <style scoped></style> |
# Home
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: "nekoaimer" }) |
| : h("span", null, "我是Home中的内容"), |
| ]); |
| }, |
| }; |
| </script> |
| |
| <style scoped></style> |
参考结果:
# 4. JSX 基本使用
vue | <script> |
| 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> |
| </div> |
| ); |
| }, |
| }; |
| </script> |
| |
| <style scoped></style> |
参考结果:
# 4.JSX 组件与插槽
# App
vue | <script> |
| import HelloWorld from "./HelloWorld.vue"; |
| import { ref } from "vue"; |
| |
| export default { |
| data() { |
| return { |
| counter: ref(0), |
| }; |
| }, |
| render() { |
| const increment = () => this.counter++; |
| const decrement = () => this.counter--; |
| const btnClick = () => { |
| this.$refs.name.textContent = "我是nekoaimer"; |
| }; |
| return ( |
| <div> |
| <h2 ref="name">当前计数:{this.counter}</h2> |
| <button onClick={increment}>+1</button> |
| <button onClick={decrement}>-1</button> |
| <HelloWorld> |
| <!--swig0--> |
| </HelloWorld> |
| </div> |
| ); |
| }, |
| }; |
| </script> |
| |
| <style scoped></style> |
# HelloWorld
vue | <script> |
| export default { |
| render() { |
| return ( |
| <div> |
| <h2>HelloWorld</h2> |
| {this.$slots.default ? ( |
| this.$slots.default({ name: "nekoaimer" }) |
| ) : ( |
| <span>Nekoaimer</span> |
| )} |
| </div> |
| ); |
| }, |
| }; |
| </script> |
| |
| <style scoped></style> |
参考结果: