Vue3从入门到精通(三)
阅读原文时间:2023年09月07日阅读:1

在 Vue3 中,插槽(Slots)的使用方式与 Vue2 中基本相同,但有一些细微的差异。以下是在 Vue3 中使用插槽的示例:

// ChildComponent.vue
<template>
  <div>
    <h2>Child Component</h2>
    <slot></slot>
  </div>
</template>
​
// ParentComponent.vue
<template>
  <div>
    <h1>Parent Component</h1>
    <ChildComponent>
      <p>This is the content of the slot.</p>
    </ChildComponent>
  </div>
</template>
​
<script>
  import { defineComponent } from 'vue'
  import ChildComponent from './ChildComponent.vue'
​
  export default defineComponent({
    name: 'ParentComponent',
    components: {
      ChildComponent
    }
  })
</script>

在上面的示例中,ChildComponent 组件定义了一个默认插槽,使用 <slot></slot> 标签来表示插槽的位置。在 ParentComponent 组件中,使用 <ChildComponent> 标签包裹了一段内容 <p>This is the content of the slot.</p>,这段内容将被插入到 ChildComponent 组件的插槽位置。

需要注意的是,在 Vue3 中,默认插槽不再具有具名插槽的概念。如果需要使用具名插槽,可以使用 v-slot 指令。以下是一个示例:

// ChildComponent.vue
<template>
  <div>
    <h2>Child Component</h2>
    <slot name="header"></slot>
    <slot></slot>
    <slot name="footer"></slot>
  </div>
</template>
​
// ParentComponent.vue
<template>
  <div>
    <h1>Parent Component</h1>
    <ChildComponent>
      <template v-slot:header>
        <h3>This is the header slot</h3>
      </template>
      <p>This is the content of the default slot.</p>
      <template v-slot:footer>
        <p>This is the footer slot</p>
      </template>
    </ChildComponent>
  </div>
</template>
​
<script>
  import { defineComponent } from 'vue'
  import ChildComponent from './ChildComponent.vue'
​
  export default defineComponent({
    name: 'ParentComponent',
    components: {
      ChildComponent
    }
  })
</script>

在上面的示例中,ChildComponent 组件定义了三个插槽,分别是名为 header、默认插槽和名为 footer 的插槽。在 ParentComponent 组件中,使用 <template v-slot:header> 来定义 header 插槽的内容,使用 <template v-slot:footer> 来定义 footer 插槽的内容。默认插槽可以直接写在组件标签内部。

需要注意的是,在 Vue3 中,v-slot 只能用在 <template> 标签上,不能用在普通的 HTML 标签上。如果要在普通 HTML 标签上使用插槽,可以使用 v-slot 的缩写语法 #。例如,<template v-slot:header> 可以简写为 #header

在 Vue3 中,组件的生命周期钩子函数与 Vue2 中有一些变化。以下是 Vue3 中常用的组件生命周期钩子函数:

  1. beforeCreate: 在实例初始化之后、数据观测之前被调用。

  2. created: 在实例创建完成之后被调用。此时,实例已完成数据观测、属性和方法的运算,但尚未挂载到 DOM 中。

  3. beforeMount: 在挂载开始之前被调用。在此阶段,模板已经编译完成,但尚未将模板渲染到 DOM 中。

  4. mounted: 在挂载完成之后被调用。此时,组件已经被挂载到 DOM 中,可以访问到 DOM 元素。

  5. beforeUpdate: 在数据更新之前被调用。在此阶段,虚拟 DOM 已经重新渲染,并将计算得到的变化应用到真实 DOM 上,但尚未更新到视图中。

  6. updated: 在数据更新之后被调用。此时,组件已经更新到最新的状态,DOM 也已经更新完成。

  7. beforeUnmount: 在组件卸载之前被调用。在此阶段,组件实例仍然可用,可以访问到组件的数据和方法。

  8. unmounted: 在组件卸载之后被调用。此时,组件实例已经被销毁,无法再访问到组件的数据和方法。

需要注意的是,Vue3 中移除了一些生命周期钩子函数,如 beforeDestroydestroyed。取而代之的是 beforeUnmountunmounted

另外,Vue3 中还引入了新的生命周期钩子函数 onRenderTrackedonRenderTriggered,用于追踪组件的渲染过程和触发的依赖项。

需要注意的是,Vue3 推荐使用 Composition API 来编写组件逻辑,而不是依赖于生命周期钩子函数。Composition API 提供了 setup 函数,用于组件的初始化和逻辑组织。在 setup 函数中,可以使用 onBeforeMountonMountedonBeforeUpdateonUpdatedonBeforeUnmount 等函数来替代相应的生命周期钩子函数。

vue3生命周期应用

Vue3 的生命周期钩子函数可以用于在组件的不同生命周期阶段执行相应的操作。以下是一些 Vue3 生命周期的应用场景示例:

  1. beforeCreatecreated:在组件实例创建之前和创建之后执行一些初始化操作,如设置初始数据、进行异步请求等。

    export default {
    beforeCreate() {
    console.log('beforeCreate hook');
    // 执行一些初始化操作
    },
    created() {
    console.log('created hook');
    // 执行一些初始化操作
    },
    };

  2. beforeMountmounted:在组件挂载之前和挂载之后执行一些 DOM 操作,如获取 DOM 元素、绑定事件等。

    export default {
    beforeMount() {
    console.log('beforeMount hook');
    // 执行一些 DOM 操作
    },
    mounted() {
    console.log('mounted hook');
    // 执行一些 DOM 操作
    },
    };

  3. beforeUpdateupdated:在组件数据更新之前和更新之后执行一些操作,如更新 DOM、发送请求等。

    export default {
    beforeUpdate() {
    console.log('beforeUpdate hook');
    // 执行一些操作
    },
    updated() {
    console.log('updated hook');
    // 执行一些操作
    },
    };

  4. beforeUnmountunmounted:在组件卸载之前和卸载之后执行一些清理操作,如取消订阅、清除定时器等。

    export default {
    beforeUnmount() {
    console.log('beforeUnmount hook');
    // 执行一些清理操作
    },
    unmounted() {
    console.log('unmounted hook');
    // 执行一些清理操作
    },
    };

这些示例展示了 Vue3 生命周期钩子函数的一些常见应用场景。根据具体需求,你可以在相应的生命周期钩子函数中执行适当的操作。

在 Vue3 中,可以使用动态组件来根据不同的条件或状态动态地渲染不同的组件。使用动态组件可以使应用更加灵活和可扩展。以下是使用动态组件的示例:

  1. 使用 component 元素和 :is 属性来实现动态组件的渲染:


在上面的示例中,根据 currentComponent 的值动态地渲染 ComponentAComponentB 组件。点击按钮时,切换 currentComponent 的值,从而实现动态组件的切换。

  1. 使用 v-ifv-else 来根据条件渲染不同的组件:


在上面的示例中,根据 showComponentA 的值使用 v-ifv-else 来渲染 ComponentAComponentB 组件。点击按钮时,切换 showComponentA 的值,从而实现动态组件的切换。

这些示例演示了在 Vue3 中如何使用动态组件来根据条件或状态动态地渲染不同的组件。你可以根据具体需求选择适合的方式来使用动态组件。

在 Vue3 中,可以使用 <keep-alive> 组件来保持组件的存活状态,即使组件在组件树中被切换或销毁,它的状态仍然会被保留。这对于需要在组件之间共享状态或缓存数据的场景非常有用。以下是使用 <keep-alive> 组件来保持组件存活的示例:

<template>
  <div>
    <button @click="toggleComponent">Toggle Component</button>
    <keep-alive>
      <component :is="currentComponent"></component>
    </keep-alive>
  </div>
</template>
​
<script>
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';
​
export default {
  data() {
    return {
      currentComponent: 'ComponentA',
    };
  },
  methods: {
    toggleComponent() {
      this.currentComponent = this.currentComponent === 'ComponentA' ? 'ComponentB' : 'ComponentA';
    },
  },
  components: {
    ComponentA,
    ComponentB,
  },
};
</script>

在上面的示例中,使用 <keep-alive> 组件将 <component> 包裹起来,这样在切换组件时,被包裹的组件的状态将会被保留。点击按钮时,切换 currentComponent 的值,从而切换要渲染的组件。

需要注意的是,被 <keep-alive> 包裹的组件在切换时会触发一些特定的生命周期钩子函数,如 activateddeactivated。你可以在这些钩子函数中执行一些特定的操作,如获取焦点、发送请求等。

<template>
  <div>
    <h2>Component A</h2>
  </div>
</template>
​
<script>
export default {
  activated() {
    console.log('Component A activated');
    // 执行一些操作
  },
  deactivated() {
    console.log('Component A deactivated');
    // 执行一些操作
  },
};
</script>

在上面的示例中,当组件 A 被激活或停用时,分别在 activateddeactivated 钩子函数中输出相应的信息。

使用 <keep-alive> 组件可以方便地保持组件的存活状态,并在组件之间共享状态或缓存数据。

在 Vue3 中,可以使用异步组件来延迟加载组件的代码,从而提高应用的性能和加载速度。异步组件在需要时才会被加载,而不是在应用初始化时就加载所有组件的代码。以下是使用异步组件的示例:

  1. 使用 defineAsyncComponent 函数来定义异步组件:


在上面的示例中,使用 defineAsyncComponent 函数来定义异步组件 AsyncComponent。当点击按钮时,设置 isComponentLoadedtrue,并将 component 设置为 AsyncComponent,从而加载异步组件。

  1. 使用 Suspense 组件来处理异步组件的加载状态:


在上面的示例中,使用 Suspense 组件来处理异步组件的加载状态。在 default 插槽中,渲染异步组件,而在 fallback 插槽中,渲染加载状态的提示信息。当点击按钮时,加载异步组件。

这些示例演示了在 Vue3 中如何使用异步组件来延迟加载组件的代码。使用异步组件可以提高应用的性能和加载速度,特别是在应用中有大量组件时。

在 Vue3 中,可以使用依赖注入来在组件之间共享数据或功能。Vue3 提供了 provideinject 两个函数来实现依赖注入。

  1. 使用 provide 函数在父组件中提供数据或功能:


在上面的示例中,使用 provide 函数在父组件中提供了一个名为 myService 的数据或功能,它的值是一个 MyService 的实例。

  1. 使用 inject 函数在子组件中注入提供的数据或功能:


在上面的示例中,使用 inject 函数在子组件中注入了父组件提供的名为 myService 的数据或功能。通过注入的 myService 实例,可以调用其中的方法或访问其中的属性。

通过使用 provideinject 函数,可以在组件之间实现依赖注入,从而实现数据或功能的共享。这在多个组件需要访问相同的数据或功能时非常有用。

Vue3 是一个用于构建用户界面的现代化 JavaScript 框架。它具有响应式数据绑定、组件化、虚拟 DOM 等特性,使得开发者可以更高效地构建交互式的 Web 应用。

下面是一些使用 Vue3 开发应用的步骤:

  1. 安装 Vue3:使用 npm 或 yarn 安装 Vue3 的最新版本。

    npm install vue@next

  2. 创建 Vue3 应用:创建一个新的 Vue3 项目。

    vue create my-app

  3. 编写组件:在 src 目录下创建组件文件,例如 HelloWorld.vue


在上面的示例中,使用 ref 函数创建了一个响应式的数据 message,并在模板中使用它。通过点击按钮,可以改变 message 的值。

  1. 使用组件:在 App.vue 中使用自定义的组件。


在上面的示例中,导入并注册了自定义的 HelloWorld 组件,并在模板中使用它。

  1. 运行应用:在命令行中运行以下命令启动应用。

    npm run serve

这将启动开发服务器,并在浏览器中打开应用。

这只是一个简单的示例,你可以根据实际需求编写更复杂的组件和应用逻辑。Vue3 还提供了许多其他功能和工具,如路由、状态管理、单文件组件等,以帮助你构建更强大的应用。

希望这个简单的示例能帮助你入门 Vue3 应用的开发!