在整个应用程序中将VueJS组件放在何处

时间:2020-01-21 09:38:24

标签: vue.js vuejs2 vue-component vuetify.js nuxt.js

在我的nuxtjs应用程序中,我在整个应用程序中使用的功能很少,即“登录/注册”对话框,用于显示警报的小吃栏等。 ,我希望每个页面上都有这些功能,并且v-app-bar组件已添加到所有页面中。我已经将这些功能的组件包括在v-app-bar组件中。

<template>
  <v-app-bar app id="app-bar">
    <LoginJoinDialog />
    <AlertSnackbar />

    <!-- Code for App bar -->

  </v-app-bar>
</template>

但是由于以下原因,我对这种方法不满意

  1. 我知道这些通用组件不属于v-app-bar组件。只是为了避免干燥和维护麻烦,我将它们包括在内。因此,从设计角度来看,这不是很直观。
  2. 第二,如果将来我的页面没有v-app-bar组件,该怎么办。在那种情况下,无论如何我将重复这些通用组件的代码。因此,在多个地方维护代码的痛苦仍然存在。

考虑到以上几点,我正在寻找一种比我已经实现的方法更优雅的方法。如果对此有vuejs条建议,那就更好了。您对这些通用功能的组件结构有什么建议?

2 个答案:

答案 0 :(得分:1)

您可以使用布局实现所需的内容。您需要做的是将layouts目录中的src文件夹。然后您可以创建尽可能多的 布局组件(* .vue文件)并根据需要使用它们。

例如,这是layouts文件夹中的 default.vue 组件:

<template>
  <main>
    <!-- Your app bar component -->
    <v-app-bar app id="app-bar">
      <LoginJoinDialog />
      <AlertSnackbar />
      <!-- Code for App bar -->
    </v-app-bar>

    <!-- Page Content (This tag will automatically embed the page content into layouts)-->
    <nuxt />

  </main>
</template>

<script>
export default {};
</script>

现在,在您的pages文件夹中,您可以添加 index.vue 文件,该文件可以通过以下方式作为属性来引用默认布局:layout: 'default'

index.vue文件应如下所示:

<template>
  <!-- page content goes here -->
</template>

<script>
export default {
  name: 'HomePage',
  layout: 'default',
};
</script>

我还创建了一个带有布局的example project in nuxt

对于该项目的工作原型:Visit this link

希望它能帮助您解决问题。

答案 1 :(得分:0)

您可以使用global component registration trick by Chris Fritz。您只需要对其进行一些修改,以使其更适合nuxt.js应用。因此,您可以在base文件夹下创建一个components文件夹,并将所有这些共享组件保留在那里。然后创建一个新的插件,并更改您的@/components/base文件夹的路径,并修改正则表达式,以便无论名称是什么,它都将捕获所有文件:

globalComponents.js

import Vue from 'vue'
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'

export default () => {
  const requireComponent = require.context(
    '@/components/base', false, /[\w-]+\.vue$/
  )

  requireComponent.keys().forEach(fileName => {
    const componentConfig = requireComponent(fileName)

    const componentName = upperFirst(
      camelCase(fileName.replace(/^\.\/(.*)\.\w+$/, '$1'))
    )

    Vue.component(componentName, componentConfig.default || componentConfig)
  })
}

nuxt.config.js

plugins: [
  '~/plugins/globalComponents.js'
],
相关问题