【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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM