使用vue-cli搭建前端環境


本實例是根據我司項目實際需求搭建,僅供參考, 本博主原創文章, 如有轉載, 請備注原文鏈接

構建項目

  • 全局安裝vue-cli(本實例中使用的2.9.6)

$ npm install -g vue-cli

  • 使用

vue init <template-name> <project-name>

  • example

$ vue init webpack my-project

  • 項目構建成功,目錄如下

  • 試運行 npm run dev,可以看到打開vue的歡迎頁

按需引入依賴包並 使用

1. element-ui ----餓了么出品的vue2.0 pc UI框架

  • 安裝

$ npm install element-ui -S

  • 使用 在src目錄下的main.js引入
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI)

2. normalize.css ----格式化css

  • 安裝

$ npm install normalize.css -S

  • 使用 在src目錄下的main.js引入
import 'normalize.css/normalize.css'

3. sass ----成熟、穩定和強大的專業級CSS擴展語

  • 安裝
    $ npm install --save-dev sass-loader
    //sass-loader依賴於node-sass
    $ npm install --save-dev node-sass
  • 頁面使用 ----app.vue中, 在style標簽中,將lang="scss"就可以使用scss語法,參考官方鏈接
<style lang="scss">

備注: 此vue-cli版本,utils已經配置好了sass,勿須像之前的版本,在build文件夾下的webpack.base.conf.js的rules里面添加配置

  • 全局配置sass,可使用全局變量
  1. --在build文件夾下下的utils文件下增加以下函數
  // 配置sass全局變量 全局文件引入 當然只想編譯一個文件的話可以省去這個函數
  function resolveResource (name) {
    return path.resolve(__dirname, '../src/style/' + name)
  }
  function generateSassResourceLoader () {
    var loaders = [
      cssLoader,
      'sass-loader',
      {
        loader: 'sass-resources-loader',
        options: {
          // 多個文件時用數組的形式傳入,單個文件時可以直接使用 path.resolve(__dirname, '../static/style/common.scss'
          resources: [resolveResource('theme.scss')]
        }
      }
    ]
    if (options.extract) {
      return ExtractTextPlugin.extract({
        use: loaders,
        fallback: 'vue-style-loader'
      })
    } else {
      return ['vue-style-loader'].concat(loaders)
    }
  }
  1. --在build文件夾下下的utils文件下修改return對象

備注: 如果要在全局使用公共變量, 必須執行上面兩步,設置全局scss環境

  • 全局引用 ---- 在main.js文件中,引入theme.scss
    import '@/style/theme.scss'

  • 全局使用

  1. 在theme.scss中,設置一個主題色
  2. 在APP.vue中使用

4. 引入lodash ---一個一致性、模塊化、高性能的 JavaScript 實用工具庫 官網鏈接

  • 安裝
    $ npm i --save lodash

  • 引用 ---- 在main.js中引用

import 'lodash'

5. 引入echarts

  • 安裝
    $ npm install echarts --save

  • 引用---- 在main.js中引用

import echarts from 'echarts'
Vue.prototype.$echarts = echarts
  • 使用

6. 引入axios ---- 一個現在主流並且很好用的請求庫 支持Promise 官方鏈接

  • 安裝
    $ npm install axios

  • 使用 第一步 ----首先設置接口請求的反向代理

  1. 在config文件夾下新增proxyConfig.js文件
module.exports = {
  proxyList: {
    '/apis': {
      target: 'http://google.com/', // 設置你調用的接口域名和端口號 別忘了加http
      // secure: false,// 如果是https接口,需要配置這個參數
      changeOrigin: true,
      pathRewrite: {
        '^/apis': '' // 這里理解成用‘/api’代替target里面的地址,后面組件中我們調接口時直接用api代替, 比如我要調用'http://google.com/user/login',直接寫‘/api/user/login
      }
    }
  }
}
  1. 在config文件夾下,打開index.js,引入配置使用
  • 使用 第二步 在src文件夾下,簡歷一個新的 api 文件夾, api文件夾下建立一個request.js文件, 用promise封裝axios
import http from 'axios'
import router from '@/router'
import {Message} from 'element-ui'
import {loadingInstance} from '@/utils/promptsMethods'

http.defaults.headers = {'Content-Type': 'application/json;charset=utf-8'}
http.defaults.responseType = 'json'
http.defaults.withCredentials = true
http.defaults.timeout = 5000

// 添加請求攔截器
http.interceptors.request.use(function (config) {
  loadingInstance()
  // 在發送請求之前做些什么
  return config
}, function (error) {
  loadingInstance().close()
  // 對請求錯誤做些什么
  return Promise.reject(error)
})

/*
  // 攔截器可按需設置, 不需要可刪除
  // 添加響應攔截器
http.interceptors.response.use(function (response) {
  loadingInstance().close()
  return response
}, function (error) {
  loadingInstance().close()
  // 對響應錯誤
  if (error.response && error.response.status === 1111) {
    Message.warning('登錄已過期! )
    router.push({path: '/login'})
  } else {
    Message.warning('網絡異常')
  }
  return Promise.reject(error)
})
*/
export function request (url, data = {}, method = 'post') {
  return new Promise((resolve, reject) => {
    const options = {
      url,
      data,
      method
    }
    http(options)
      .then(res => {
        resolve(res.data)
      })
      .catch(error => {
        reject(error)
      })
  })
} 
  • 使用 第三步 在api文件夾下, 新建 modules 文件夾, 之下建立login.js
import {request} from '../request'

const api = {
  login (params) {
    return request('/apis/user/login', params)
  }
}

export default api

目錄結構如下:

使用 在App.vue中使用

npm run dev 運行查看 login接口調用狀態

7. 使用 babel-polyfill 來兼容低版本瀏覽器 (IE 瀏覽器下)

原因, axios 是基於 promise 來實現的,IE 和低版本的設備不支持 promise。

  • 安裝
    $ npm install babel-polyfill -S

使用, ---- //main.js中引用

import 'babel-polyfill'

在我這個項目當中對axios進行了封裝, 所以,移動到 src/api/resuest.js

接着在 webpack.base.conf.js 中,將原來的

entry: {
  app: './src/main.js'
}

替換成

entry: ['babel-polyfill', './src/main.js'],

8. nprogress 進度條

  • 安裝
    $ npm install nprogress
  • 引入

配置路由 router

  • 第一步: 在src文件夾下新建文件夾=->頁面 login / dashboard / 404 /layout

  • 第二步 配置路由
    //src文件下, 新建router文件夾, 建立index.js

import Vue from 'vue'
import Router from 'vue-router'

import Layout from '@/pages/layout/layout'

/*
* hidden: true                   if `hidden:true` will not show in the sidebar(default is false)
* redirect: noredirect           if `redirect:noredirect` will no redirect in the breadcrumb
* name:'router-name'             the name is used by <keep-alive> (must set!!!)
* meta : {
    title: 'title'               the name show in submenu and breadcrumb (recommend set)
    icon: 'svg-name'             the icon show in the sidebar
    breadcrumb: false            if false, the item will hidden in breadcrumb(default is true)
  }
*/

export const constantRouterMap = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/pages/login/login'),
    hidden: true
  },
  {
    path: '/404',
    component: () => import('@/pages/404/404'),
    hidden: true
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    name: 'Dashboard',
    hidden: true,
    children: [
      {
        path: 'dashboard',
        component: () => import('@/pages/dashboard/dashboard')
      }
    ]
  },
  {
    path: '/external-link',
    component: Layout,
    children: [
      {
        path: 'https://panjiachen.github.io/vue-element-admin-site/#/',
        meta: { title: 'External Link', icon: 'link' }
      }
    ]
  },

  { path: '*', redirect: '/404', hidden: true }
]

Vue.use(Router)

export default new Router({
  // mode: 'history', //后端支持可開
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRouterMap
})

  • 第三步 配置路由權限
    // 在src文件夾下, 新建 permission.js
import router from './router'
import NProgress from 'nprogress' // Progress 進度條
import 'nprogress/nprogress.css'// Progress 進度條樣式

const whiteList = ['/login'] // 不重定向白名單
router.beforeEach((to, from, next) => {
  NProgress.start()
  // next()

  if (whiteList.indexOf(to.path) !== -1) {

    next()
  } else {
    next(`/login`) // 否則全部重定向到登錄頁
    NProgress.done()
  }
})

router.afterEach(() => {
  NProgress.done() // 結束Progress
})

  • 第四步 執行命令 npm run dev 到登錄頁面

目錄結構 (此時,上面未提及的未配置的文件夾是之后要繼續配置的)

此時 簡單的前端環境搭建完成 之后會持續更新, 權限控制和vuex的使用

------------------------------------------------------------------------------------------------------------------------------------

9. vuex ----數據狀態管理, 官方參考連接

  • 安裝
    $ npm install vuex

  • 使用

生產環境移除console, debugger信息

//webpack.prod.conf.js

替換成

    new UglifyJsPlugin({
      uglifyOptions: {
        compress: {
          warnings: false,
          drop_debugger: true,
          drop_console: true,
          pure_funcs: ['console.log'] // 移除console.log
        }
      },
      sourceMap: config.build.productionSourceMap,
      parallel: true
    })


免責聲明!

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



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