📢 公告
微信公众号二维码

欢迎大家关注我的公众号

Skip to content

Vue3 | 使用render方法创建组件

《Vue.js 3 Cookbook》

1、创建一个HTML文件

HTML文件的初始内容如下:

html
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>基础框架</title>
  <script src="https://unpkg.com/vue@next"></script>
</head>
<body>
  <div id="app">
  </div>
  <script></script>
</body>
</html>

本示例中,我们使用<script>标签直接通过CDN引入Vue。

2、声明defineComponenthcreateApp

js
const {
  defineComponent,
  h,
  createApp
} = Vue;

使用解构赋值语法,从Vue对象中提取defineComponentcreateApp方法,将它们赋值给变量defineComponentcreateApp中。其中createApp用于创建Vue实例,defineComponent用于定义组件。

3、创建组件

js
const component = defineComponent({
  data: () => ({
    // 定义一个属性,用于计数
    count: 0
  }),
  methods: {
    // 定义方法,调用时count属性加1
    addOne() {
      this.count += 1;
    }
  },
  // 组件模板
  template: `
    <h1>Vue 3 根元素</h1>
    <button @click="addOne">点了{{ count }}次</button>
  `
});

在Vue3中,我们可以使用defineComponent方法定义一个组件,defineComponent方法的参数为一个JavaScript对象。在本示例中,我们使用了datamethodstemplate3个属性。

4、创建vue实例

使用createApp创建vue实例,将vue实例挂载到HTML DOM元素上。

js
createApp(component).mount('#app');

使用createApp创建vue实例,参数为前面创建的组件。vue实体用于管理和挂载组件。调用mount()方法将vue实例挂载到HTML DOM元素上。


当根组件没有设置 template 选项时,Vue 将自动使用容器的 innerHTML 作为模板。

h()渲染函数API:https://cn.vuejs.org/api/render-function.html#h