如何在组件中使用全局常量

第一步,在 src 下新建 const 文件夹下 新建 const.js

.
├── src
│   ├── const
│   │    ├── const.js
│   │    
│   └── main.js
└── ...

第二步,如何在 const.js 文件下,设置常量

export default {

    install(Vue,options){

        Vue.prototype.global = {
            title:'全局',
            isBack: true,
            isAdd:  false,
        };
        
    }

 }

第三步,在 main.js 下全局引入:

//引入全局常量
import constant from './const/const.js'
Vue.use(constant);

第四步,即可在 .vue 组件中使用:

//通过js方式使用:
this.global.title
//或在 html 结构中使用
{{global.title}}

问题二:在 JS 中使用全局常量

第一步,在 src 下新建 const 文件夹下 新建 type.js

.
├── src
│   ├── const
│   │    ├── type.js
│   │    
│   └── main.js
└── ...

第二步,在 type.js 文件下,设置常量

export const TEST_INCREMENT='TEST_INCREMENT'
export const TEST_DEREMENT='TEST_DEREMENT'

第三步,在其他 .js 文件下引入并使用:

//以对象的形式引入:
import * as types from '../types'
//使用:
types.TEST_INCREMENT
posted @ 2020-07-25 16:34  duqianqian  阅读(339)  评论(0编辑  收藏  举报