VUE之组件全局方法

时间:2022-06-13
本文章向大家介绍VUE之组件全局方法,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

全局方法其实是js自身就可以实现的方法,具体实现其实很简单, 比如加个日志显示组件:

export default {	
  created(){
    var _this = this
      window.error= function(msg,title){
        _this.error(msg,title)
      }
      window.info= function(msg,title){
        _this.info(msg,title)
      }
       window.debug= function(msg,title){
          _this.debug(msg,title)
      }
     },
     name:"Log",
      ...
}

调用就很简单啦:

window.error(msg,title)
//或者
error(msg,title)

是不是感觉特方便,比起那个什么总线简直强到不知哪去去了。。。

还有更加变态一点的做法:

export default {	
  created(){
      window.$log = this
  },
  methods{
      error(msg,title){
          ...
      }
  }
...
}

调用就很方便了:

$log(msg,title)

当然,别忘了把组件加入到界面,最好加入在App.vue里面:

<template>
  <div id="app">
    <div class="content">    	
    		<router-view/>
    		<Log />
    </div>    
  </div>
</template>
<script>

import Logfrom '@/components/Log'

export default {
  name: 'App',
  components:{
  	"Log":Log
  }
}
</script>