html - vue如何定义一个变量,让所有组件都能使用
伊谢尔伦
伊谢尔伦 2017-04-17 14:59:13
0
5
901

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

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(5)
巴扎黑

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

洪涛

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

左手右手慢动作

API.js

var API='xxxxx';
exports.API=API;

import API from './API'

API.API
小葫芦

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

Peter_Zhu

Global variable window or vuex

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template