17
社区成员




在 Vue.js 中,可以使用 export
关键字来导出常量,然后在其他组件或页面中使用该常量。以下是一个示例:
在一个名为 constants.js
的文件中,定义一个名为 MY_CONSTANT
的常量,并使用 export
语法将其导出:
export const MY_CONSTANT = 'This is my constant.';
在需要使用 MY_CONSTANT
的组件或页面中,首先使用 import
语法导入该常量,然后在代码中使用该常量:
<template>
<div>
<h1>Hello World</h1>
<p>{{ myConstant }}</p>
</div>
</template>
<script>
import { MY_CONSTANT } from './constants.js'
export default {
name: 'App',
data() {
return {
myConstant: MY_CONSTANT
}
}
}
</script>
在上面的示例中,我们在 App.vue
文件中导入了 MY_CONSTANT
常量,并在 data
选项中定义了一个名为 myConstant
的数据属性,将其值设置为 MY_CONSTANT
。然后,我们在模板中使用了 {{ myConstant }}
语法来呈现该常量。
需要注意的是,在导入常量时,需要使用正确的文件路径和常量名称。此外,在导入常量时,需要使用大括号 {}
将常量名称括起来,以避免与默认导出混淆。