Home  >  Q&A  >  body text

html - vue如何定义一个变量,让所有组件都能使用

如图,每个get和post请求都一个url,项目进行太多的数据交互 所以需要把每个url的相同部分定义成一个变量,
这样方便以后修改 但我不懂如何在vue里面定义一个公共变量,让所有组件都能使用。希望大家帮帮忙,谢谢

伊谢尔伦伊谢尔伦2741 days ago847

reply all(5)I'll reply

  • 巴扎黑

    巴扎黑2017-04-17 15:01:13

    main.js

    import domain from './domain.js';
    global.domain = domain;

    domain.js

    const domain = '//192.168.1.117:1009/';
    
    export default {
        testUrl: domain + '/cas/doc/docTypeList'
    }

    The structure shown above can solve the management of request URLs in large and medium-sized Vue applications. The author can introduce the domain.js in main.js and expose it as a global variable, which can be used in each component. Obtain the corresponding url address set through domain.testUrl.
    The benefits are as follows:

    • Centralized url management to facilitate later management and modification

    • Convenient coding, just pass domain.testUrl in the request

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 15:01:13

    This seems to have nothing to do with vue. If you are using ES6, you can use the const module.

    // api.js
    
    export const BASE_URL = '//192.168.1.117:1009/'
    ... ...

    Call:

    import { BASE_URL } from 'api'
    
    this.$http.get(`{BASE_URL}/cas/doc/docTypeList`)
    ... 

    For this kind of problem, you can learn from the solution defined for modules in redux.
    vue also has the same model: vuex

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 15:01:13

    API.js

    var API='xxxxx';
    exports.API=API;
    
    import API from './API'
    
    API.API
    

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 15:01:13

    Write a Vue plug-in. The plug-in is global.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 15:01:13

    Global variable window or vuex

    reply
    0
  • Cancelreply