开发中会经常用到一些常用的变量和方法 例如ajax这种
一、给vue定义全局变量
1.定义专用模块来配置全局变量
定义一个专用模块来配置全局变量,然后通过export暴露出去,在需要的组件引入global.vue
// 定义一些公共的属性和方法
const httpUrl = 'http://test.com'
// 暴露出这些属性
export default {
    httpUrl,
}
引入及使用
<script>
    // 导入共用组件
    import global from './global.vue'
    export default {
        data () {
            return {
                //使用
                globalUrl: global.httpUrl
            }
        }
    }
</script>
2.通过全局变量挂载到Vue.prototype
同上,定义一个专用模块来配置全局变量,然后通过export暴露出去,在需要的组件引入global.vue
// 定义一些公共的属性和方法
const httpUrl = 'http://test.com'
// 暴露出这些属性
export default {
    httpUrl,
}
在main.js中引入并复制给vue
// 导入共用组件
import global from './global.vue'
Vue.prototype.global = global
组件调用
export default {
    data () {
        return {
           // 赋值使用, 可以使用this变量来访问
           globalHttpUrl: this.global.httpUrl
    }
}
3.使用vuex
安装:
npm install vuex --save
新建store.js文件
import Vue from 'vue'
import Vuex from 'vuex'; 
Vue.use(Vuex); 
export default new Vuex.Store({ 
    state:{ httpUrl:'http://test.com' } 
})
main.js中引入
import store from './store'
new Vue({
    el: '#app', 
    router, 
    store, 
    components: { App }, 
    template: '<App/>' 
});
组件内调用
console.log(this.$store.state.httpUrl)
二、给vue定义全局方法
1.将方法挂载到 Vue.prototype 上面
简单的函数可以直接写在main.js文件里定义。
// 将方法挂载到vue原型上
Vue.prototype.changeData = function (){
  alert('执行成功');
}
使用方法
//直接通过this运行函数,这里this是vue实例对象
this.changeData();
2. 利用全局混入 mixin
新建一个mixin.js文件
export default {
    data() {
    },
    methods: {
        randomString(encode = 36, number = -8) {
            return Math.random() // 生成随机数字,
                .toString(encode) // 转化成36进制
                .slice(number) 
        }
    }
}
// 在项目入口 main.js 里配置
import Vue from 'vue'
import mixin from '@/mixin'
Vue.mixin(mixin)
// 在组件中使用
export default {
    mounted() {
        this.randomString()
    }
}
3. 使用插件方式
plugin.js文件,文件位置可以放在跟main.js同一级,方便引用
exports.install = function (Vue, options) {
    Vue.prototype.test = function (){
        console.log('test');
    };
};
main.js引入并使用。
import plugin from './plugin'
Vue.use(plugin);
所有的组件里就可以调用该函数。
this.test();