如何通过基于页面的路由打开模式时nuxt 3重置滚动?

问题描述 投票:0回答:1
问题:在我的NUXT应用中打开模式 /灯箱时,使用基于页面的路由,它重置了父页面的滚动。 我希望在打开模态时保留滚动位置!

我一直在网上尝试许多不同的解决方案,但尚未找到相关的解决方案。 NUXT路由器中是否有任何配置?

在以下示例中复制:

index中的thing 5行约50次(因此在您的浏览器中出现滚动条)

op

/

(index.vue)
    croll降低,然后单击任何链接
  1. observe:模态出现,但是crolling重置在父页面上
  2. 在模态仍打开时滚动。有趣的:这滚动了父页面
    单击模态以关闭它。
    OBSERVE:
  3. 关闭模态没有重置滚动(很好!)
  4. /pages/index.vue:
  5. <template> <ol> <li><NuxtLink :href="'/session/1'">Thing 1</NuxtLink></li> <li><NuxtLink :href="'/session/2'">Thing 2</NuxtLink></li> <li><NuxtLink :href="'/session/3'">Thing 3</NuxtLink></li> <li><NuxtLink :href="'/session/4'">Thing 4</NuxtLink></li> <li><NuxtLink :href="'/session/5'">Thing 5</NuxtLink></li> </ol> <LazyNuxtPage /> </template>
  6. /pages/index/session/[id] .vue:
  7. <script setup lang="ts"> import { useRoute, useRouter } from 'vue-router'; import { watch } from 'vue'; const route = useRoute(); const router = useRouter(); </script> <template> <div :style="{ position: 'fixed', top: '16px', right: '16px', backgroundColor: '#cccccc', padding: '8px' }"> Thing {{ route.params.id }}. <button @click="router.push('/')">(Close overlay)</button> </div> </template>
  8. 您之所以出现问题,是因为模式是在页面/session/[id] .vue中定义的,这使其成为NUXT中的新基于路由的页面。当您导航到模态(例如 /session /1)时,NUXT将其视为全页导航,这会导致父页面重置其滚动位置。
  9. 为什么会发生这种情况? 由于session/[id] .vue是一个页面组件,因此NUXT假定它应该替换当前视图。 即使您将其作为覆盖层进行样式,NUXT仍将其作为新页面加载,从而导致卷轴重置。
启用通过NUXTLINK处理模态和路由更改,使用一个全局模态组件,该组件可以打开而无需远离页面。

index.vue

<template> <ol> <li><button @click="openModal(1)">Thing 1</button></li> <li><button @click="openModal(2)">Thing 2</button></li> <li><button @click="openModal(3)">Thing 3</button></li> <li><button @click="openModal(4)">Thing 4</button></li> <li><button @click="openModal(5)">Thing 5</button></li> </ol> <!-- Modal Component --> <Modal :isOpen="isModalOpen" @close="isModalOpen = false"> <p>Thing {{ selectedThing }} Details</p> </Modal> </template> <script setup> import { ref } from 'vue'; import Modal from '@/components/Modal.vue'; const isModalOpen = ref(false); const selectedThing = ref(null); const openModal = (thingId) => { selectedThing.value = thingId; isModalOpen.value = true; }; </script>

[id].vue
vue.js nuxt.js vue-router nuxt3.js
1个回答
0
投票

<template> <div v-if="isOpen" class="modal-overlay" @click.self="closeModal"> <div class="modal-content"> <slot /> <button @click="closeModal">Close</button> </div> </div> </template> <script setup> import { defineProps, defineEmits } from 'vue'; defineProps(['isOpen']); const emit = defineEmits(['close']); const closeModal = () => { emit('close'); }; </script> <style scoped> .modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.5); display: flex; justify-content: center; align-items: center; } .modal-content { background: white; padding: 20px; border-radius: 8px; } </style>

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.