这看起来很愚蠢,但我的设置如下:

config/index.js年:

module.exports = {
    API_LOCATION: 'http://localhost:8080/api/'
}

src/app.js年后我有:

import Vue from 'vue'
import VueRouter from 'vue-router'
import VueResource from 'vue-resource';

Vue.use(VueRouter);
Vue.use(VueResource);

const App = require("./app.vue");
const home = require("./components/home.vue");
const config = require('../config');
window.config = config;

然后在src/components/home.vue中,我有一个脚本块,使用它如下:

<script>
    module.exports = {
        data: function() {
            return {
                obj: null
            }
        },
        created: function() {
            this.$http.get(config.API_LOCAITON + '/call').then(res => {
                // Do some business
            }, res => {
                // Handle some error
            });
        }
    }
</script>

这是可行的,但我觉得用window来处理应用程序配置是个坏主意.这里更规范的方法是什么?

推荐答案

导入它.

<script>
    import config from "../config"

    module.exports = {
        data: function() {
            return {
                obj: null
            }
        },
        created: function() {
            this.$http.get(config.API_LOCATION + '/call').then(res => {
                // Do some business
            }, res => {
                // Handle some error
            });
        }
    }
</script>

或者只是位置.

<script>
    import { API_LOCATION } from "../config"

    module.exports = {
        data: function() {
            return {
                obj: null
            }
        },
        created: function() {
            this.$http.get(API_LOCATION + '/call').then(res => {
                // Do some business
            }, res => {
                // Handle some error
            });
        }
    }
</script>

Vue.js相关问答推荐

Vue 3 在一个值更改问题后再次重新渲染每一行

Nuxt3: 安装vue3-spinner (error: require is not defined in ES module scope)

绑定事件在渲染函数中不起作用

如何使用 vue.js 获取本地 html 文件?

使用 vuex 更新数据

Vue.js 中有没有类似Jquery $(document).ready的功能?

在按键 vuejs 中只允许数字和一个小数点后 2 位限制

如何在 vue 3 脚本设置中使用

使用 vue-property-decorator 时注册本地组件

Vuetify / Offline离线图标

vuetify:以编程方式显示对话框

Modal 内部的 Vue.js AJAX 调用

如何从 v-for 创建的对象中绑定多个类?

过渡后的 v-if 下方的过渡元素

Laravel 和 Vue - handler.call 不是函数

emit更新数组不起作用

如何在 vue.js 中进行嵌入?

如何在 vuejs 中的基于类的组件中编写计算设置器

如何将单选按钮绑定到 vuex store ?

vuejs 中缺少 webpack 配置