Nuxt 打开链接到模态

Aye*_*azo 10 javascript vue.js vue-router nuxt.js

我正在构建一个包含产品列表的Nuxt应用程序,然后单击其中一个打开该产品的专用页面。它工作正常。

结构是:

/pages/featured // directory of products
/pages/product/:id/:slug // Dedicated product page
Run Code Online (Sandbox Code Playgroud)

现在我想添加一个新功能:

  • 如果从不是产品目录的页面点击或人们直接登陆该页面,我希望保留产品的专用页面;
  • 如果显然是从目录中单击,我希望在目录顶部打开一个几乎全屏的产品对话框;
  • 保持对话框上的路由更改。

我希望实现的一个很好的例子是Youpic的 photo 目录。

“产品”列表,完全在带有内部导航的对话框中可见。

我正在查看各种nuxt-routingvue-router文档以尝试开发它,但我离解决方案还很远。

我在这里看到的一小部分代码看起来与我需要的非常相似,但我不明白我应该如何正确实现它以及如何创建我的 nuxt 自定义路由:

export default {
  router: {
    extendRoutes (routes, resolve) {
      routes.push({
        path: '/users/:id',
        components: {
          default: resolve(__dirname, 'pages/users'), // or routes[index].component
          modal: resolve(__dirname, 'components/modal.vue')
        },
        chunkNames: {
          modal: 'components/modal'
        }
      })
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

ajo*_*obi 14

我在这里为您构建了一个沙盒解决方案:https : //codesandbox.io/s/reverent-leftpad-xj81p

解释解决方案:

该解决方案使用默认情况下可用于您的 nuxt 页面的beforeRouteLeave()函数vue-router

beforeRouteLeave(to, from, next) {
  if (to.name === "product-id") {
    this.displayProductModal(to);
  } else {
    next();
  }
},
Run Code Online (Sandbox Code Playgroud)

此功能会在特色页面上的任何路线更改发生之前中断它们,如果目标路线是产品详细信息的路线(这意味着有人点击了产品链接),它会打开模态对话框。

要处理打开和关闭模态时的 url 更改,使用该window.history对象:

displayProductModal(route) {
  this.activeModal = route.params.id
  window.history.pushState({}, null, route.path)
},
hideProductModal() {
  this.activeModal = null
  window.history.pushState({}, null, this.$route.path)
}
Run Code Online (Sandbox Code Playgroud)

尝试一下,它应该与您提供的 Youpic 示例完全相同。

注意:示例中没有使用真正的“模态”,为了简单起见,整个示例尽可能基本。