vue - Vue.prototype.$xx和Vue.use()的使用详解

  Vue.prototype和Vue.use()在项目中并不存在什么关系,主要是看个人喜欢的使用方式。下面我来说说我如何使用这两个的:

1、使用Vue.prototype.$xx的情况

  在做一个项目的时候,我会习惯性的将某些方法直接绑定到原型上面,然后直接通过this点出来就可以使用了,当然,这个是在多个页面都用到的时候我会选择这样做。
  举个例子:
   在main.js文件中写入:

import { Toast } from 'mint-ui';
Vue.prototype.$toast = Toast;
		    
import Axios from 'axios';
Vue.prototype.$http = Axios;

    用到的页面:

this.$toast("处理数据过程发生错误");
		
this.$http(url, [{
     headers: {
     	Authorization: "Bearer " + sAser.storage('token')
     },
     dataType: 'jsonp',
     crossDomain: true,
}]).then((res)=>{
     console.log(res)
}).catch((err)=>{
      console.log(err)
})

2、使用Vue.use()的情况

  当每个页面都需要使用到的插件、方法,直接使用vue.use()全局注入,这样我们就不需要在每个页面都单独引入了。
  举个例子:

import Vue from 'vue';
import Router from 'vue-router';
import Vuex from 'vuex';
		    
Vue.use(Router);
Vue.use(Vuex);
发布了44 篇原创文章 · 获赞 8 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/LiaoFengJi/article/details/98494207