vue中main.js個人理解就是我們在項目中使用到的一些插件的集合
一般比較常使用的有 vue.use(實現原理)
那vue.use 會自動阻止多次注冊相同插件,屆時只會注冊一次該插件 Vue 是可訪問的全局變量時會自動調用 Vue.use()
vue.prototype 自我理解延伸原形
下邊就貼一下自己在實際項目中的main.js 的配置
import 'babel-polyfill'
import Vue from 'vue'
import App from './App'
import router from './router'
import '../static/css/common.css'
import './utils/global'
import rem from "../static/js/rem.js";
使用element-ui 和 rem 布局
//element-ui
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI)
Vue.use(rem)
import Vuetree from 'vue-simple-tree'
Vue.use(Vuetree);
import 'iview/dist/styles/iview.css';
這是自己寫一個存儲的方法 可以引進來直接使用
//存儲
import tool from "./utils/tool.js";
Vue.prototype.$tool = tool;
工具類同上
//工具類
import uitls from './utils/utils'
Vue.prototype.$utils = uitls;
Vue.prototype.$tool = tool;
axios的使用 以及 設置請求超時的時間 還有全局方法添加請求頭
//axios
import axios from "axios";
import vueAxios from "vue-axios";
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Vue.prototype.axios = axios;
Vue.prototype.axios = axios.create({
timeout: 600000
});
//設置請求頭
Vue.prototype.axios.interceptors.request.use((config) => {
let userInfo = uitls.getCookie('username');
if (userInfo) {
config.headers.Authorization = 'bearer ' + JSON.parse(uitls.getCookie('username')).value.access_token;
注意:我所使用的請求頭可能不是你所需要的,所以需要看自身的情況來寫這里的邏輯 比如userInfo 可以自己定義任何東西
}
return config;
}, (error) => {
return Promise.reject(error);
});
這一塊是抓取錯誤的返回值,因為后台可能會有一些不是報錯的報錯,比如 412 瀏覽器認為是錯誤,但其實可能是沒有權限之類的東西,但是在代碼中console也獲取不到這個錯誤信息 所以 可以使用下面的方法
import { Message } from 'element-ui';
Vue.prototype.$message = Message;
Vue.prototype.axios.interceptors.response.use(response => {
return response;
}, error => {
if(error && error.response.status){
switch (error.response.status) {
case 400:
error.messages = "錯誤請求";
Message.error('錯誤信息:400');
可能會有人問為什么提示錯誤信息要這么寫,注意:又有一個知識點,在main.js 無法直接使用 this.$message 所以Vue.prototype.$message = Message;
break
case 412:
Message.error('錯誤信息:412');
break
case 500:
Message.error('錯誤信息:500');
break
case 504:
Message.error('錯誤信息:504');
break
}
return error.response;
}
})
import VideoPlayer from 'vue-video-player'
require('video.js/dist/video-js.css')
require('vue-video-player/src/custom-theme.css')
Vue.use(VideoPlayer)
vuex的引入,應該都會的
//vuex
import store from "./store/index";
import 'swiper/dist/css/swiper.css'
Vue.prototype.$vm = new Vue();
Vue.config.productionTip = false;
//滾動條
import HappyScroll from 'vue-happy-scroll'
// 引入css
import 'vue-happy-scroll/docs/happy-scroll.css'
Vue.use(HappyScroll)
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
components: { App,HappyScroll },
template: '<App/>'
})
小白一枚,如有幸幫到你,那真是極好,如有錯誤,還請多多指正,感激不盡。