vue-cli中定义全局变量 或 方法(函数)

一.定义不变的vue全局变量

一般我们都会定义一些 常量,比如基础的访问域名, 静态资源版本号。

可以将该常量绑定到vue的全局属性上即可:

[html]  view plain  copy

[html]  view plain  copy
  1. 1.函数  
[html]  view plain  copy
  1. Vue.prototype.baseUrl = function () {  
  2.       return 'http://csdn.net';  
  3.     };  
[html]  view plain  copy
  1. 2.变量  
  2. Vue.prototype.getTitle = {  
  3.       title:'',  
  4.       isBack: true,  
  5.       isAdd:  false,  
  6.     };  

添加方法( 在vue-cli中使用 ):

1直接将上面任一个 改代码放入 ''src/main.js" 中, 即可定义全部变量。

2类似这种配置, 可以单独起一个配置文件,

(1)可以在项目的src 目录里面 新建一个 lib目录 。lib目录里创建一个 config目录, 然后在config目录里新建一个config.js文件.

vue-cli中定义全局变量 或 方法(函数)_第1张图片

(2)然后在config.js文件里写上

[html]  view plain  copy
  1. export default {  
  2.   install(Vue,options)  
  3.   {  
  4.     Vue.prototype.baseUrl = function () {  
  5.        return '111';  
  6.     };  
  7.     Vue.prototype.getTitle = {  
  8.       title:'',  
  9.       isBack: true,  
  10.       isAdd:  false,  
  11.     };  
  12.     Vue.prototype.showFootTab = {  
  13.       isShow:false,  
  14.       active:0,  
  15.     }  
  16.   }  
  17. }  

(3)最后还要在vue-cli里面引用

           在 根目录下的 main.js中 添加下面两行代码即可

      

[html]  view plain  copy
  1. import config from './lib/config/config.js'  
  2.   
  3. Vue.use(config);  

 以上就可以定义全局变量了。


2使用方法

(1)直接在模版中调用

[html]  view plain  copy
  1. <template>  
  2.   <div>  
  3.     {{getTitle.title}}  
  4.   div>  
  5. template>  

  (2)js代码中使用


[html]  view plain  copy
  1. this.getTitle  

你可能感兴趣的:(vue.js)