使用vue-cli搭建前端環境

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

構建項目

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

$ npm install -g vue-cli
css

  • 使用

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

  • example

$ vue init webpack my-project
前端

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

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

按需引入依賴包並 使用

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

  • 安裝

$ npm install element-ui -S
vue

  • 使用 在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
java

  • 使用 在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裏面添加配置node

  • 全局配置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環境webpack

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

  • 全局使用
    git

  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
    })
相關文章
相關標籤/搜索