1、创建应用并挂载到页面中:

import { createApp } from 'vue'  // 1、引用vue方法
import App from './App.vue'  // 从一个单文件组件中导入根组件

const app = createApp(App);  // 2、添加根组件
/* 
或者:
const app = createApp({
  //根组件选项
});
*/

app.mount('#app') // 3、挂载应用;app为html的标签,如: <div id="app"></div>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.

  注:①.mount() 方法应该始终在整个应用配置和资源注册完成后被调用。同时请注意,不同于其他资源注册方法,它的返回值是根组件实例而非应用实例。

    ②页面支持多个应用挂载,如下:

const app1 = createApp({
  /* ... */
})
app1.mount('#container-1')

const app2 = createApp({
  /* ... */
})
app2.mount('#container-2')
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

2、应用配置:

  应用配置必须在被挂载前完成

  1)注册全局组件

    方式一():

import { createApp } from 'vue'

  const app = createApp({})

  app.component(
    // 组件1-注册的名字
    'MyComponent',
    // 组件的实现
    {
      /* ... */
    }
    .component(
    // 组件2-注册的名字
    'MyComponent',
    // 组件的实现
    {
      /* ... */
    }
    .component(
    // 组件3-注册的名字
    'MyComponent',
    // 组件的实现
    {
      /* ... */
    }
  )
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.

    方式二(使用单文件组件时):

import MyComponent from './App.vue'

  app
    .component('ComponentA', ComponentA)
    .component('ComponentB', ComponentB)
    .component('ComponentC', ComponentC)


...使用
<!-- 这在当前应用的任意组件中都可用;三个组件彼此独立 -->
<ComponentA/>
<ComponentB/>
<ComponentC/>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.

  组件的详细知识见:Vue3 学习笔记(七)——Vue组件的使用

  补充-全局变量与局部变量的区别:

    ① 全局注册,但并没有被使用的组件无法在生产打包时被自动移除 (也叫“tree-shaking”)。如果你全局注册了一个组件,即使它并没有被实际使用,它仍然会出现在打包后的 JS 文件中。

    ② 全局注册在大型项目中使项目的依赖关系变得不那么明确。在父组件中使用子组件时,不太容易定位子组件的实现。和使用过多的全局变量一样,这可能会影响应用长期的可维护性。

  2)捕获全局异常
app.config.errorHandler = (err) => {
       /* 处理错误 */
    }
  • 1.
  • 2.
  • 3.

作者:꧁执笔小白꧂