Vue自定义函数挂载到全局方法

使用export default + install + Vue.prototype

方法写在哪,怎么写,一般按项目规则和个人习惯

我这里以$http为例

1.创建request文件夹,创建index.js文件,写入方法

const $http = function(...){ //全局方法最好用$开头
    ...
}
export default vueHttp = {
    install(Vue){
        ...
        Object.defineProperty(Vue.prototype,'$http',{
            value:$http,
            writable:false
        })//这里使用了数据绑定的方法,下面给出学习链接
    }
}
export {$http}

2.在main.js中写入函数

import http from '@/request'
Vue.use(http)

3.在所有组件里可调用函数

this.$http(...);

猜你喜欢

转载自blog.csdn.net/weixin_46772652/article/details/107933321
今日推荐