在我的 vue 项目中全局导入常量的最佳实践是什么,在我的例子中是一个 ENUMS。
我看到了一个解决方案,就是把它添加到 Vue 的实例中这样
import { Type } from './models/Type.js'
new Vue({
router,
Type,
render: h => h(App)
}).$mount('#app')
但是没有效果
最佳答案
const
是保留关键字,您可以使用其他名称,如 myConst
并基于此 tip
尝试:
Vue.prototype.$myConst=4;
new Vue({
router,
render: h => h(App)
}).$mount('#app')
并使用 this.$myConst
在您的应用中的任何地方引用它。
// ignore the following two lines, they just disable warnings in "Run code snippet"
Vue.config.devtools = false;
Vue.prototype.$myConst=4444;
new Vue({
el: '#app',
created(){
console.log(this.$myConst)
}
});
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app" class="container">
<h1>test : {{this.$myConst}}</h1>
</div>
关于javascript - 使用 Vue js 全局定义一个常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57729182/