在 Nuxt 中存储常量的最佳方法是什么?

Ric*_*cou 14 constants vue.js nuxt.js

我有一个 nuxt 项目(vuejs),我想知道如何在我的项目中存储常量?(大约 50 个常量)。

谢谢您的答复。卡布梅

Bir*_*nte 12

我可以创建一个 constants.js 文件和

 // constants.js
 export const CONSTANT_1 = 'CONSTANT_1';
 export const CONSTANT_2 = 'CONSTANT_2';
 export const CONSTANT_3 = 'CONSTANT_3';

 // And call it like this
 import { CONSTANT_1 } from 'constants';
Run Code Online (Sandbox Code Playgroud)

谢谢


stw*_*ilz 7

我认为@Birante 是正确的。仅仅因为某些文件夹不随样板提供并不意味着您不能添加它们。但是我会提出一个这样的结构,

|-- assets
|
|-- components
|   |-- Logo.vue
|   `-- index.js
|
|-- constants
|   |-- constants_002.js
|   |-- constants_001.js
|   `-- index.js
|
|-- layouts
|   |-- default.vue
|   `-- index.js
|
|-- middleware
|   `-- index.js
|
|-- pages
|   `-- index.vue
|
|-- plugins
|
|-- static
|
|-- store
|   `-- index.js
|
|-- test
|   `-- Logo.spec
|
`-- package.json
Run Code Online (Sandbox Code Playgroud)

然后以模块化方式设置常量,就像设置应用程序的任何其他部分一样。

常量/常量_001.js

export const MY_FIRST_CONSTANT = 'is awesome'
Run Code Online (Sandbox Code Playgroud)

常量/常量_002.js

export const MY_SECOND_CONSTANT = 'is also awesome'
Run Code Online (Sandbox Code Playgroud)

常量/index.js

export * from './constants_001';
export * from './constants_002';
Run Code Online (Sandbox Code Playgroud)

然后,您可以根据整个应用程序中使用的约定导入常量。

import { MY_FIRST_CONSTANT, MY_SECOND_CONSTANT } from '@/constants/'
Run Code Online (Sandbox Code Playgroud)

这也是utils您需要在整个应用程序中共享的一个很好的约定:)


小智 5

没有最好的方法取决于项目和开发人员的风格和项目的需求。

在我的一些项目中,我创建了本地文件夹breadcrumbi18n在其上存储了一些数据。

之后constants.jslocal文件夹中创建文件并在其上插入常量。像下面

const X="X";
const Y="Y";

export {
  X,
  Y
}
Run Code Online (Sandbox Code Playgroud)

之后只是简单使用,不需要在每个文件中导入它们我需要它们为下面创建插件

import * as Constants from '@/locale/constants';

export default ({ app }, inject) => {
    inject('constants', Constants)
}
Run Code Online (Sandbox Code Playgroud)

之后我可以在每个需要的文件中使用它们,如下所示

this.$constants.X
Run Code Online (Sandbox Code Playgroud)