温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

vue怎么定义全局变量和全局方法

发布时间:2023-04-25 14:57:16 来源:亿速云 阅读:108 作者:zzz 栏目:开发技术

本篇内容介绍了“vue怎么定义全局变量和全局方法”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

一、给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();

“vue怎么定义全局变量和全局方法”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue
AI