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

看了不少方法介绍,基本思路是,定义方法->在main.js中引入->就能全局使用,提升代码的复用性。我这里只写下工做中常见和经常使用的方法html

使用export default + install + Vue.prototypevue

方法写在哪,怎么写,通常按项目规则和我的习惯函数

我这里以$http为例学习

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

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

 

2.在main.js中写入函数spa

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

3.在全部组件里可调用函数prototype

this.$http(...);

 

 

数据绑定学习连接:https://www.jianshu.com/p/c02cb881bea8code

参考:htm

http://www.javashuo.com/article/p-rztszvui-dq.htmlblog

http://www.javashuo.com/article/p-aipofcll-dk.html

https://www.jianshu.com/p/8ec5e1233ffe

相关文章
相关标签/搜索