公司企業站Vue-CLI4開發環境搭建詳解


1.安裝

npm install -g @vue/cli    //vue-cli2.x的安裝命令是 cnpm install -g vue-cli

安裝好了以后我們可以輸入如下命令進行校驗,看是否成功安裝了

vue -V

如下圖所示,表示安裝成功了


2.項目創建

安裝好了CLI4之后,我們就可以在指定的目錄中創建項目了,命令行進入到指定目錄中,然后輸入如下命令創建項目:

vue create my-project

通過上下箭頭按鍵選擇第二個選項(手動選擇特性)

根據項目需求選擇配置如下圖:

TypeScript 支持使用 TypeScript 書寫源碼
Progressive Web App (PWA) Support PWA 支持。
Router 支持 vue-router 。
Vuex 支持 vuex 。
CSS Pre-processors 支持 CSS 預處理器。
Linter / Formatter 支持代碼風格檢查和格式化。
Unit Testing 支持單元測試。
E2E Testing 支持 E2E 測試。

注意,空格鍵是選中與取消,A鍵是全選 ,選擇完成后按回車

選擇路由模式(hash或history)

選擇css預處理方式,這里我選擇的第二個選項

選擇ESLint代碼檢查方式,我選擇的是第一個,只要代碼不符合ESLint規范就報錯並阻止運行。這里我想說的是,因為本人編程比較奔放,代碼向來都是洋洋灑灑,實在適應不了那些條條框框,寫完代碼之后都是用編譯器進行格式化的,安裝ESLint也是預留給習慣使用的程序猿用的。
 

選擇保存是進行代碼檢查

將eslint和babel放在單獨文件進行配置還是在packet.json文件中進行配置,這里我選的是第一個
是否要保留以上配置作為以后項目的常用配置,我選的是不保存
這些選項配置好了就可以等待項目安裝了
 
如果出現 Cannot download "https://github.com/sass/node-sass/releases/download/binding.nod的問題
cnpm i node-sass --sass_binary_site=https://npm.taobao.org/mirrors/node-sass/

在控制台輸入如下命令啟動項目:

cd my-project // 進入到項目根目錄
npm run serve // 啟動項目

在瀏覽器中訪問http://localhost:8080/index#/

 

3. 依賴包的安裝

在控制台中安裝css-loader,style-loader(用於解析阿里iconfont圖標),vant,animation,axios
安裝css-loader和style-loader,
安裝vant
 
cnpm install css-loader --save-dev
cnpm install style-loader --save-dev
cnpm install vant --save

在main.js中引入vant,添加如下代碼:

import Vant from 'vant';
import 'vant/lib/index.css';
Vue.use(Vant);

安裝animation

cnpm install animate.css --save

在main.js中添加如下代碼:

import animate from 'animate.css'

安裝axios

cnpm install axios --save

在main.js中添加如下代碼:

import axios from 'axios'
Vue.prototype.axios=axios

iconfont矢量圖引入:
阿里矢量圖標官網上選擇需要用到的圖標,然后下載到本地,解壓縮之后將如下文件進行復制,並在public文件夾中創建iconfont文件夾,把這些文件粘貼到里面


在main.js中添加如下代碼

import '../public/iconfont/iconfont.css';
安裝 postcss-plugin-px2remlib-flexible插件,postcss-plugin-px2rem用於將移動端px單位自動轉換成rem單位,lib-flexible可以實現移動端多種屏幕自適應;其中px自動轉rem的插件網上有許多,比如postcss-pxtorem,postcss-px2rem,postcss-pxtorem-exclude(exclude屬性不好用,有可能是我配置有問題,至今沒找到原因)等,通過多次實踐對比,我還是推薦使用postcss-plugin-px2rem,這個插件配置選項上有 exclude屬性,它可以配置是否對某個文件夾下的所有css文件不進行從px到rem的轉換,所以我們可以利用這個特性,把項目中的 node_module文件夾排除掉。這樣如果我們項目中是用了,前端UI框架的話,就不會吧UI框架(如:Element等)中的 px單位轉換成rem了,也可以自行通過正則進行匹配。安裝命令如下:
cnpm install postcss-plugin-px2rem --save-dev

在main.js中添加如下代碼:

import 'lib-flexible';

下面我們來看一下目前為止main.js中的完整代碼:

import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
import 'lib-flexible';
import '../public/iconfont/iconfont.css';
import animate from 'animate.css'
import Vant from 'vant';
import 'vant/lib/index.css';
import axios from 'axios';
Vue.prototype.axios=axios;
Vue.config.productionTip = false;
Vue.use(Vant);

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')
安裝好了之后,我們需要進行插件的配置,有別於cli2的配置目錄結構,cli4的配置需要在項目根目錄中創建vue.config.js文件,然后在里面進行項目的各種配置,下面是我配置好的postcss-plugin-px2rem,接口代理,eslint配置項,如下:
// vue.config.js
module.exports = {
    // 輸出文件目錄
    outputDir: 'dist',
    // eslint-loader 是否在保存的時候檢查
    lintOnSave: false,
    css: {
        loaderOptions: {
            postcss: {
                plugins: [
                    require('postcss-plugin-px2rem')({
                        rootValue: 37.5, //換算基數, 默認100  ,這樣的話把根標簽的字體規定為1rem為50px,這樣就可以從設計稿上量出多少個px直接在代碼中寫多上px了。
                        // unitPrecision: 5, //允許REM單位增長到的十進制數字。
                        //propWhiteList: [],  //默認值是一個空數組,這意味着禁用白名單並啟用所有屬性。
                        // propBlackList: [], //黑名單
                        exclude: /(page_pc)/i,  //默認false,可以(reg)利用正則表達式排除某些文件夾的方法,例如/(node_module)/ 。如果想把前端UI框架內的px也轉換成rem,請把此屬性設為默認值
                        // selectorBlackList: [], //要忽略並保留為px的選擇器
                        // ignoreIdentifier: false,  //(boolean/string)忽略單個屬性的方法,啟用ignoreidentifier后,replace將自動設置為true。
                        // replace: true, // (布爾值)替換包含REM的規則,而不是添加回退。
                        mediaQuery: false,  //(布爾值)允許在媒體查詢中轉換px。
                        minPixelValue: 3 //設置要替換的最小像素值(3px會被轉rem)。 默認 0
                    }),
                ]
            }
        }
    },
    // 基本路徑
    publicPath: process.env.NODE_ENV === 'production'
        ? './'
        : '/smile-client/',
    devServer: {
        host: 'localhost',
        port: 8080,
        open: true,
        hotOnly: true, // 熱更新
        proxy: {
            '/smile-client': { // 本地mock服務器
                target: 'http://192.168.1.17:8888',
                changeOrigin: true,
                ws: false,
                pathRewrite:{
                    '^/smile-client':''    //這里理解成用‘/smile-client'代替target里面的地址,后面組件中我們調接口時直接用api代替 比如我要調用'http://codetpx.lncwkj.com/xxx/duty?age=30',可在axios的url中直接寫‘smile-client/xxx/duty?age=30'即可
                }                
            }          
        } // 設置代理
    },
  

}

4.項目開發

以上這些環境搭建好了之后,我們就可以開發項目了,首先我們要判斷瀏覽器是pc端還是移動端環境,然后跳轉不同的路由來實現加載不同的頁面,項目src目錄結構如下:

page_m用於存放移動端代碼
page_pc用於存放pc端代碼
router里用於配置路由
tools文件用於存放自己的工具類
store用於存放vuex
components用於存放公共組件
assets用於存放自己的項目靜態資源(非第三方引入)
App.vue代碼如下(寫入判斷pc端還是移動端,然后根據情況跳轉路由):
<template>
  <div id="app">
    <router-view/>
  </div>
</template>


<script>
export default {
  methods:{
        _isMobile() {
            //判斷當前環境是pc端還是移動端
             let flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
             return flag;
        }
  },
  mounted(){
    if (this._isMobile()) {
      alert("手機端");
      this.$router.replace('/home1');
    } else {
      alert("pc端");
      this.$router.replace('/about');
    }   
  }
}
</script>

<style lang="scss">
html{
    margin: 0px;
    padding: 0px;
}
body{
    margin: 0px;
    padding: 0px;
}
</style>

router/index.js路由配置如下:

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../page_m/Home.vue'
import About from '../page_pc/About.vue'

//const originalPush = VueRouter.prototype.push;
//VueRouter.prototype.push = function push(location) {
//  return originalPush.call(this, location).catch(err => err);
//};
Vue.use(VueRouter)

const routes = [
  {
    path: '',
    redirect: '/home1'
  },
  {
    path: '/home1',
    name: 'home1',
    component: Home
  },
  {
    path: '/about',
    name: 'about',
    component: About
  },  
]

const router = new VueRouter({
  routes
})

export default router

tools/service.js用於封裝axios,其中需要安裝qs,cnpm install qs --save,代碼如下:

import axios from 'axios'    //引入axios
import qs from 'qs' 
import Vue from 'vue'
import router from '../router'
let baseURL=process.env.BASE_URL.toString();//獲取配置好的基礎路徑,直接使用process.env.API_BASE並不是字符串,所以這里要轉換
axios.defaults.baseURL = baseURL;//baseURL用於自動切換本地環境接口和生產環境接口
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
axios.defaults.withCredentials = true;
//封裝axios,用於異步操作的同步寫法,與async結合使用
const api={
    get(url,data){
        //get接口封裝
        return new Promise((resolve,reject)=>{
            axios.get(url,{params:data}).then((res)=>{
                resolve(res)
            }).catch((err)=>{
                reject(err);
            })
        })
    },
    post(url,data){
        //post接口封裝
        return new Promise((resolve,reject)=>{
            axios.post(url,qs.stringify(data)).then((res)=>{
                resolve(res)
            }).catch((err)=>{
                reject(err);
            })
        })      
    },
    filePost(url,data){
        //文件上傳接口封裝
        return new Promise((resolve,reject)=>{
            axios.post(url,data).then((res)=>{
                resolve(res)
            }).catch((err)=>{
                reject(err);
            })

        })      
    }    
}

export {api,axios}

Home.vue含有annimte.css怎樣與vue聯合使用示例、vant組件引入示例,scss使用示例,axios封裝后接口調用示例,代碼如下:

<template>
  <div class="home">
    <van-button type="primary" size="normal" @click="handleClick">普通按鈕</van-button>
        <transition enter-active-class="animated" leave-active-class="animated hinge">
            <img alt="Vue logo" src="../assets/logo.png" v-show="showFlag">
        </transition>   

    <div class="icon-box">
        <div class="iconfont icon-home"></div>
    </div>
        <van-button type="warning">警告按鈕</van-button>
        <van-button type="danger">危險按鈕</van-button>    
  </div>
</template>

<script>
    
import qs from 'qs'
import { api, axios } from "../tools/service.js" //封裝axios方法    
    
export default {
  name: 'home',
  data(){
    return {
        showFlag:true,
    }
  },
  methods:{
    handleClick(){
        this.showFlag=!this.showFlag;
            //獲取所有員工列表
            api.get('user/deparyment/edit/getDeparymentList').then((res) => {
                console.log(res);
            }).catch((res) => {

            })          
    }
  },
  mounted(){
    
  }
}
</script>
<style lang="scss" scoped>
.icon-box{
    height: 100px;
    width: 100px;
    text-align: center;
    line-height: 100px;
    border: solid 1px #333;
    .icon-home{
        font-size: 30px;
    }       
}

</style>

About.vue代碼如下:

<template>
    <div class="header">
        <div class="nav"></div>
    </div>
</template>

<script>
</script>

<style lang="scss" scoped>
.header{
    .nav{
        width: 1360px;
        height: 50px;
        background-color: blue;
        margin-left: auto;
        margin-right: auto;
    }
}
</style>

原文:

https://www.jianshu.com/p/01949e4f1245

 


免責聲明!

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



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