一、新建項(xiàng)目
使用vue-cli3構(gòu)建一個(gè)初始的Vue項(xiàng)目:Cli3 官方文檔
以下配置是我在項(xiàng)目中常用的,大家可自己斟酌是否需要使用!
1、環(huán)境變量
主要用于區(qū)分 開發(fā)、測試、正式環(huán)境的
(1) 在根目錄新建三個(gè)文件:.env.dev.env.test.env.prod
(2).env.dev寫入
NODE_ENV = 'development'VUE_APP_CURRENTMODE = 'test'
(3).env.test寫入
NODE_ENV = 'production'VUE_APP_CURRENTMODE = 'test'
(4).env.prod寫入
NODE_ENV = 'production'VUE_APP_CURRENTMODE = 'prod'
(5) 修改package.json的script
"scripts": {? ? "serve": "vue-cli-service serve",? ? "build": "vue-cli-service build",? ? "lint": "vue-cli-service lint"}
修改為
"scripts":{"serve":"vue-cli-service serve --mode dev",// 本地運(yùn)行"btest":"vue-cli-service build --mode test",// 測試環(huán)境打包"build":"vue-cli-service build --mode prod",// 正式環(huán)境打包"lint":"vue-cli-service lint"}
(5) 在main.js寫入
// 是否為測試環(huán)境Vue.prototype.$istest=process.env.VUE_APP_CURRENTMODE==='test'console.log('當(dāng)前NODE_ENV:'+process.env.NODE_ENV)console.log('當(dāng)前VUE_APP_CURRENTMODE:'+process.env.VUE_APP_CURRENTMODE)console.log('是否為測試環(huán)境:'+Vue.prototype.$istest)
(6) 重啟npm run serve,這里就不要使用vue ui啟動(dòng)項(xiàng)目了,反正我通過它啟動(dòng)后,無法獲取process.env.VUE_APP_CURRENTMODE的值,只能通過命令行運(yùn)行npm run serve啟動(dòng)
控制臺(tái)打印結(jié)果:

image
2、別名設(shè)置
(1) 在vue.config.js頂部新增
// path依賴constpath=require('path')// 查找文件方法constresolve=dir=>{returnpath.join(__dirname,dir)}
(2) 在vue.config.jsmodule.exportschainWebpack新增
// 別名配置config.resolve.alias.set('assets',resolve('src/assets')).set('components',resolve('src/components'))
(3) 重啟npm run serve生效
若你使用的別名是圖片路徑的話
1、普通引入圖片:需要這樣使用<img src="~assets/img1.jpg" />,不能省略~
2、動(dòng)態(tài)引入圖片:需要這樣使用<img :src="require('assets/img2.jpg')" />,不能加上~
3、css背景圖:background-image: url('~assets/img1.jpg'),不能省略~
3、全局Sass配置
在使用sass時(shí),難免會(huì)書寫一些常用的變量、函數(shù)、混合等,除了變量可以繼承外,其他的只能在當(dāng)前文件生效,那豈不是我需要在每一個(gè).vue里面的<style lang="scss">手動(dòng)引入@import '~@/style/mixin.scss';。答案肯定是不用啦,完全可以配置成全局的
(1) 在vue.config.jsmodule.exports新增
// SASS配置css:{loaderOptions:{sass:{data:'@import "@/style/app.scss";'}}}
(2) 在src新建style文件夾,然后在style新建app.scss
// 一些變量$primary:#3398ff;$success:#29cc7a;$danger:#ee6869;// 一些混合@mixin primary{color:$primary;}@mixin success{color:$success;}@mixin danger{color:$danger;}// 一些循環(huán)@for$ifrom12through30{.f#{$i} {font-size:1px*$i!important;}}
(3) 重啟npm run serve,然后在.vue使用
在<style lang="scss">中使用
.div1{color:$primary;// 使用scss變量}.div2{@includesuccess;// 使用scss混合}
在template中使用
<divclass="f24">使用scss循環(huán)生成的類名(.f12~.f30)f代表:font-size</div>
4、全局默認(rèn)Css配置
在public/index.html里面的<head>新增<style>即可
如
<style>* {? ? margin: 0;? ? padding: 0;? ? font-family: 'Microsoft YaHei', '微軟雅黑', 'PingFang SC', Arial;? ? -webkit-font-smoothing: antialiased;? ? -moz-osx-font-smoothing: grayscale;}</style>
5、基礎(chǔ)組件的自動(dòng)化全局注冊(cè)
(1) 在src/components新建global.js
importVuefrom'vue'// 找到components文件夾下以.vue命名的文件constRC=require.context('.',true,/\.vue$/)RC.keys().forEach(fileName=>{constcomponentConfig=RC(fileName)// 因?yàn)榈玫降膄ilename格式是: './baseButton.vue', 所以這里我們?nèi)サ纛^和尾,只保留真正的文件名letcomponentName=fileName.replace(/^\.\//,'').replace(/\.\w+$/,'')letindex=componentName.indexOf('/')if(index!==-1)componentName=componentName.substr(index+1)Vue.component(componentName,componentConfig.default||componentConfig)})
(2) 在main.js里面引入
import'./components/global'
(3) 不用重啟,直接在.vue里面template寫組件即可
<hello-world/>
6、Vuex配置
(1) 安裝依賴:cnpm i -S vuex-persistedstate
vuex在刷新后會(huì)重新更新狀態(tài),但是有時(shí)候我們并不希望如此。例如全局相關(guān)的,如登錄狀態(tài)、token、以及一些不常更新的狀態(tài)等,我們更希望能夠固化到本地,減少無用的接口訪問,以及更佳的用戶體驗(yàn)。
vuex-persistedstate:即可解決,可將值放到sessionStorage或localStorage中
(2) 在src/store.js修改
importVuefrom'vue'importVuexfrom'vuex'Vue.use(Vuex)exportdefaultnewVuex.Store({state:{},mutations:{},actions:{}})
修改為
importVuefrom'vue'importVuexfrom'vuex'importcreatePersistedStatefrom'vuex-persistedstate'Vue.use(Vuex)exportdefaultnewVuex.Store({state:{// token信息token:''},mutations:{save(state,[key,data,local=false]){if(!key)thrownewError('mutations save need key!')constkeyPath=key.split('.')constlen=keyPath.lengthconstlastKey=keyPath.pop()letneedSave=statefor(leti=0;i<len-1;i++){needSave=needSave[keyPath[i]]}if(!needSave.hasOwnProperty(lastKey)){thrownewError(`【${key}】 Error Key: ${lastKey}`)}needSave[lastKey]=dataif(local){window.sessionStorage.setItem(key,JSON.stringify(data))}}},plugins:[createPersistedState({storage:window.sessionStorage})]})
(3) 無需重啟,直接刷新頁面即可成功使用vuex
(4) 在.vue中,執(zhí)行
this.$store.commit('save',['token','token2'])
即可改變 state.token 的值
7、Vue-Router配置
(1) 安裝依賴:cnpm i -S vue-router-auto
vue-router-auto:將項(xiàng)目文件自動(dòng)轉(zhuǎn)為相應(yīng)的路由配置
(2) 在src/route.js修改
importVuefrom'vue'importRouterfrom'vue-router'importHomefrom'./views/Home.vue'Vue.use(Router)exportdefaultnewRouter({mode:'history',base:process.env.BASE_URL,routes:[{path:'/',name:'home',component:Home},{path:'/about',name:'about',// route level code-splitting// this generates a separate chunk (about.[hash].js) for this route// which is lazy-loaded when the route is visited.component:()=>import(/* webpackChunkName: "about" */'./views/About.vue')}]})
修改為
importVuefrom'vue'importRouterfrom'vue-router'importautoRouterfrom'vue-router-auto'// 引入依賴if(!window.VueRouter)Vue.use(Router)// 自動(dòng)生成路由數(shù)據(jù)constroutes=autoRouter({redirect:'/home',rc:require.context('@/views',true,/\.vue$/)})// 將生成的路由數(shù)據(jù),掛載到 new RouterexportdefaultnewRouter({mode:'history',base:process.env.BASE_URL,routes})
8、api請(qǐng)求配置
(1) 安裝依賴:cnpm i -S axios hzq-axios
hzq-axios:對(duì) axios 請(qǐng)求的二次封裝,封裝成 Vue 插件 this.$api ,并支持Axios請(qǐng)求、響應(yīng)攔截
(2) 在src下,新建apiurl文件夾,在apiurl文件夾下新建index.js
exportdefault[{name:'GetImageCaptcha',url:'/Captcha/GetImageCaptcha'}]
(3) 在main.js里引入并使用:
importhzqAxiosfrom'hzq-axios'Vue.use(hzqAxios,require.context('@/apiurl',true,/\.js$/),{baseURL:'/api',// 請(qǐng)求攔截之前beforeRequest(config){console.log(config)returnconfig},// 接口響應(yīng)成功事件respSuccess(res){console.log(res)},// 接口響應(yīng)失敗事件respError(e){console.log(e)}})
(4) 在vue.config.jsmodule.exports新增devServer的設(shè)置
devServer:{// 代理proxy:{'/giftapi':{target:'http://***.***.com',ws:true,changeOrigin:true}}}
(5) 重啟npm run serve生效
(6) 在.vue中,這樣使用
this.$api.GetImageCaptcha().then(res=>{if(res.code===1){console.log(res.data)}})
9、Vue全局方法、變量配置
(1) 安裝依賴:cnpm i -S hzq-tool
hzq-tool:基于 Vue 對(duì)一些常用的工具函數(shù)進(jìn)行封裝,通過this.$tool調(diào)用
(2) 在main.js引入并使用
importhzqToolfrom'hzq-tool'Vue.use(hzqTool)
(3) 無需重啟,在.vue里面使用
constb={name:'12'}consta=this.$tool.copy(b)// 深拷貝方法this.$setItem('id','123456')// 往sessionStorage存入數(shù)據(jù)
原文鏈接:http://m.itdecent.cn/p/d7250d185532