返回

Nuxt3 全局弹窗:用动画和数据传递提升用户体验

前端

Nuxt3:打造一个华丽的全局弹窗(附动画)

厌倦了乏善可陈的弹窗?让我们用 Nuxt3 亲手打造一个惊艳四座的全局弹窗,为你的应用程序增添一抹灵动。

优雅的出场方式

我们引入 <Transition> 组件,为弹窗出场增添一丝视觉魔力。当弹窗出现时,它将以迷人的淡入动画滑入视野,消失时则以淡出动画优雅退场。

灵活的数据传递

我们的弹窗可不仅仅是好看的皮囊,它还支持灵活的数据传递。使用 <Teleport> 组件,我们可以轻松将弹窗移动到应用程序任何位置,无论是在当前组件树中还是外部。

TypeScript 的强力支持

为了让你的开发过程更加顺畅,我们支持 TypeScript,让你可以充分利用它的类型系统和 IntelliSense 功能,尽享编码乐趣。

实战指南

1. 创建弹窗组件

components 目录下新建一个文件 Modal.vue

<template>
  <transition name="fade">
    <div class="modal-container">
      <div class="modal-content">
        <slot></slot>
      </div>
    </div>
  </transition>
</template>

<script>
import { defineComponent, ref, onMounted } from 'vue';
import { useTeleport } from 'vue-teleport';

export default defineComponent({
  setup() {
    const visible = ref(false);
    const teleportTarget = ref(null);
    const teleport = useTeleport(teleportTarget);

    onMounted(() => {
      visible.value = true;
    });

    return {
      visible,
      teleport,
      teleportTarget,
    };
  },
});
</script>

<style>
.modal-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 5px;
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.2s ease-in-out;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
}
</style>

2. 创建全局组件

plugins 目录下新建一个文件 modal.client.js

import { defineNuxtPlugin, useHead } from '@nuxtjs/composition-api';

export default defineNuxtPlugin(() => {
  const head = useHead();

  head.addScript({
    src: '/modal.js',
  });
});

3. 创建脚本文件

assets 目录下新建一个文件 modal.js

import Vue from 'vue';
import Modal from '~/components/Modal.vue';

Vue.component('NModal', Modal);

4. 使用弹窗

在你的组件中使用弹窗:

<template>
  <div>
    <button @click="showModal">Open Modal</button>
    <n-modal v-if="visible">
      <h1>Hello from Modal!</h1>
    </n-modal>
  </div>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const visible = ref(false);

    const showModal = () => {
      visible.value = true;
    };

    return {
      visible,
      showModal,
    };
  },
};
</script>

结论

恭喜你!你现在已经拥有了一个优雅、实用且易于使用的 Nuxt3 全局弹窗。有了这个秘密武器,你的应用程序将更加美观、功能强大。尽情发挥你的想象力,打造惊艳的界面,为你的用户带来难忘的体验吧!