【Vue】Vue怎么定义全局方法

一、将方法挂载到Vue.prototype上面

缺点:调用该方法得时候没有提示

//grobal.js
const RandomString =(encode = 36 ,number = -8) =>{
      return Math.random() //生成随机数,eg:0.1234
           .toString(encode) //转化成36进制 :“0,4fy”
           .slice(number)   
},
 
export default{
     RandomString
 
}
//在项目的入口文件里配置
import Vue from 'vue'
import global from "@/global"
Object.key(global).forEach((key)=>{
    Vue.prototype["$global"+key] =global[key]
})
//挂载之后,在需要引入全局变量的模块处(App.vue),不需要再导入全局变量模块,而是直接用this就可以引用了如下:
export default{ 
    mounted(){ 
          this.$globalRandomString()
    } 
}   

二、利用全局混入mixin

优点:因为mixin里面的methods会和创建的每个单文件组件合并。这样做的优点是调用这个方法的时候有提示

import moment from 'moment'
const mixin ={
  methods:{
       minRandomString(encode = 36 ,number =-8){
           return Math.random().toString(encode).slice(number)    
      }
}
//在项目入口的mian.js里配置
import Vue from "vue"
import mixin from "@/mixin"
Vue.mixin(mixin)
//使用文件
export default{
     mounted(){ 
        this.minRandomString()
     }    
}

三、使用Plugin

Vue.use的实现并没有实现挂载的功能,只是触发了插件的install方法,本质上使用了Vue.prototype

// base.js
const install = function (Vue, opts) {
    Vue.prototype.$pluginDemo = function () {
        console.log('我已经在Vue原型链上')
    }
}
export default {
    install
}
//main.js
//注册全局函数
import base from 'service/base';
Vue.use(base);
export default{ 
    mounted(){
       this.$pluginDemo() 
    } 
}

四、任意vue文件中写全局函数

//创建全局方法
this.$root.$on('test',function(){
   console.log("test")
})
//销毁全局方法
this.$root.$off("test')
//调用全局方法
this.$root.$emit("test")

转自:https://www.cnblogs.com/bbldhf/p/13916690.html

原文地址:https://www.cnblogs.com/vickylinj/p/14409326.html