VUE指南-搭建后台管理平台


開發工具:webstorm

 

一、VUE可視化管理創建項目:

(1)Win + R運行對話框,輸入CMD打開命令提示符彈窗,輸入vue ui運行vue項目管理器

(2)項目配置

  • 點擊底部“在此創建新項目按鈕”,輸入項目名(必須為英文),選擇項目預設。(手動基礎配置建議選擇:Babel/Router/CSS Pre-processors)
  • 1.是否需要歷史模式,不需要不用管。默認將使用兼容更好的哈希模式路由安裝。Use history mode for router?
  • 2.Pick a CSS pre-processor:選擇Sass/SCSS (with node-sass),(node-sass是自動編譯實時的,dart-sass需要保存后才會生效)Pick a CSS pre-processor
  • 是否需要保存為項目預設方便下次使用,創建項目不需要保存

 

(3)插件與依賴安裝

  • 在插件欄中,點擊右上角添加插件,搜索axios並安裝。
  • 在依賴欄中,點擊右上角添加依賴,搜索element-ui並安裝。

 

(4)目錄清理

<template>
  <div id="app">
    <router-view/>
  </div>
</template>

 

(5)啟動項目

  • 點擊任務欄,選擇serve運行,點擊啟動app

 

 

二、創建代碼托管倉庫:(可跳過)

(1)如果沒有碼雲SSH公鑰 創建教程:https://gitee.com/help/articles/4181

(2)新建倉庫后,上傳新增項目到碼雲中。在項目根目錄Terminal中運行:git remote add origin https://gitee.com/Alex_Tian/tstest.git

(3)如果提示碼雲的賬號密碼錯誤,清除賬號密碼 重新輸入 git config --system --unset credential.helper    由於linux輸入密碼都不反顯,輸入完成回車就行。

 

 

三、配置路由Router

import Vue from 'vue'
import VueRouter from 'vue-router'

// ——————————————————————————————
// 頁面進度條
// ——————————————————————————————
import NProgress from 'nprogress'//引入nprogress
import 'nprogress/nprogress.css' //這個樣式必須引入
NProgress.inc(0.1);
NProgress.configure({easing: 'ease', speed: 500, showSpinner: false});

// ——————————————————————————————
// 路由重復解決
// ——————————————————————————————
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
};

import Vue from 'vue'
import VueRouter from 'vue-router'

// ——————————————————————————————
// 頁面進度條
// ——————————————————————————————
import NProgress from 'nprogress'//引入nprogress
import 'nprogress/nprogress.css' //這個樣式必須引入
NProgress.inc(0.1);
NProgress.configure({easing: 'ease', speed: 500, showSpinner: false});

// ——————————————————————————————
// 路由重復解決
// ——————————————————————————————
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
};

// ——————————————————————————————
// 創建路由
// ——————————————————————————————
/**其他*/
const Dashboard = () => import('../views/dashboard/index'); // 根目錄
const Login = () => import('../views/login/index');// 登錄
const Welcome = () => import('../views/home/welcome');// 歡迎
Vue.use(VueRouter);

const routes = [
  /**
   * redirect: 路由重定向
   * */
  {
    path: '/',
    redirect: '/welcome',
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },

  //資源管理
  {
    path: '/swResourceManage',
    name: '資源管理',
    component: Dashboard,
    children: [
      {
        path: '/organization',
        component: Organization,
        name: '二級',
        children: [
          {
            path: '/organizationUpdata',
            component: OrganizationUpdata,
            name: '三級',
          },
        ]
      },
    ]
  },
];

// ——————————————————————————————
// 進入某個路由之前(掛載導航守衛)
// ——————————————————————————————
router.beforeEach((to, from, next) => {
  // to 將要訪問的路徑
  // from 從來跳轉而來
  // next 函數,表示放行  next():放行  next('/'):要強制跳轉的路徑

  // 頁面進度條開始
  NProgress.start();
  
  // 訪問登錄頁,放行
  if (to.path === '/login') return next();

  // 訪問頁面是否有token,有放行,沒有跳轉登錄頁
  const tokenStr = window.sessionStorage.getItem('accessToken');
  if (!tokenStr) return next('/login');
  next()
});


// ——————————————————————————————
// 進入某個路由之后
// ——————————————————————————————
router.afterEach((to, from, next) => {
  console.log(to.meta.title);
  if (to.meta.title) {
    document.title = to.meta.title;    //在路由里面寫入的meta里面的title字段
  }

  // 頁面進度條結束
  NProgress.done();

  // 默認結束回到頂部
  window.scrollTo(0, 0)
});

export default router

 

 

四、封裝request.js

  • 根目錄新增plugins文件夾,創建request.js
/**引入axios、路由、Element的消息提醒*/
import axios from 'axios'
import router from '../router'
import {Message} from 'element-ui'

/**創建一個axios實例*/
const service = axios.create({
  baseURL: 'http://******/', // api地址
  timeout: 5000 // 請求超時時間
});


/**添加請求攔截器*/
// 在請求或響應被 then 或 catch 處理前攔截它們
// 登陸請求服務器沒有發令牌,不能放在登陸中
service.interceptors.request.use(function (config) {
  // 在發送請求之前做些什么(請求頭放入token)
  config.headers.accessToken = window.sessionStorage.getItem('accessToken');
  // 固定寫法最后return config
  return config
}, function (error) {
  // 對請求錯誤做些什么
  return Promise.reject(error)
});

/**添加響應攔截器*/
service.interceptors.response.use(response => {
  // 對響應數據做點什么(如果返回的狀態碼不是0或是-1 就主動報錯)
  const res = response.data;
  if (res.code !== 0 || res.code === -1) {
    Message({
      message: res.msg,
      type: 'warning',
      duration: 3000
    });

    // 如果狀態碼超時,重新登錄
    if (res.code === 10003) {
      router.push('/login');
      window.sessionStorage.clear()
    }
    return Promise.reject(new Error(res.data.msg || 'Error'))
  } else {
    return res.data
  }
}, error => {
  console.log('err' + error) // for debug
  Message({
    message: error.message,
    type: 'error',
    duration: 5 * 1000
  })
  return Promise.reject(error)
})

/** 統一封裝GET請求*/
export const get = (url, params, config = {}) => {
  return new Promise((resolve, reject) => {
    service({
      method: 'GET',
      url,
      params,
      ...config
    }).then(response => {
      console.log(response)
      resolve(response)
    }).catch(error => {
      reject(error)
    })
  })
};

/** 統一封裝POST請求*/
export const post = (url, data, config = {}) => {
  return new Promise((resolve, reject) => {
    service({
      method: 'POST',
      url,
      data,
      ...config
    }).then(response => {
      resolve(response)
    }).catch(error => {
      reject(error)
    })
  })
};

export default service

 

 

 五、配置api接口地址

  • 根目錄新增api文件夾,創建integration.js
import service from '../plugins/request'

// ——————————————————————————————
// 控制台
// ——————————————————————————————
/**
 * 數據概覽(完成)
 */
export const getDataOverview = (params) => service.get(`/manage/dataOverview/getDataOverview`, params);

/**
 * 操作日志查詢(含分頁)
 */
export const opGetPageAndParam = (data) => service.post(`/manage/operationLog/getPageAndParam`, data);

 

 

六、使用Postman測試api接口(可跳過)

  • 在postman中輸入接口地址,在Headers中填入token(登錄除外),在Body中填入參數,在X-WWW 填入鍵值對的參數,點擊send按鈕測試接口。
  • 如果后台發的是json格式的文檔,點擊頂部左上角的Import,點擊Upload Files按鈕導入使用。

 

 

七、api接口優化

  • 在src根目錄下創建api目錄,api目錄中包含index.js(接口輸出)和integration.js(全部接口管理)
  • 在main.js中引入index.js 
import '@/api/index' // api
  • index.js 輸入接口
import Vue from 'vue'
import integration from './integration'

Vue.prototype.$api = {
  integration
};
  • integration.js 接口管理
import request from '../plugins/request'

// ——————————————————————————————
// 登錄相關
// ——————————————————————————————
/**
 * 獲取當前登錄的菜單權限
 * @params username 賬號 默認admin
 * @params password 賬號 默認123456
 */
const userLogin = (data) => request({
  url: '/manage/admin/login',
  method: 'post',
  data
});

/**
 * 獲取當前登錄的菜單權限
 * @params username type 默認傳1
 */
const getUserMenuList = (params) => request({
  url: '/manage/userMenuResource/getUserMenuList',
  method: 'GET',
  params
});

export default {
  userLogin,
  getUserMenuList
}

 

八、vue.config.js 配置

const path = require('path');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;   //導入可視化打包分析

module.exports = {
  /**
   * productionSourceMap:
   * 如果你不需要生產環境的 source map,可以將其設置為 false 以加速生產環境構建。
   * */
  productionSourceMap:false,

  /**
   * runtimeCompiler:是否使用包含運行時編譯器的 Vue 構建版本。
   * 設置為 true 后你就可以在 Vue 組件中使用 template 選項了,但是這會讓你的應用額外增加 10kb 左右。
   * */
  runtimeCompiler: true,

  /**
   * publicPath; 設置部署應用包時的基本URL
   * 這個值也可以被設置為空字符串 ('') 或是相對路徑 ('./'),
   * 這樣所有的資源都會被鏈接為相對路徑,這樣打出來的包可以被部署在任意路徑。
   * */
  publicPath: './',

  /**
   * lintOnSave:是否在保存的時候使用 `eslint-loader` 進行檢查
   * 當設置為 `"error"` 時,檢查出的錯誤會觸發編譯失敗。
   * */
  lintOnSave: false,

  /**
   * configureWebpack:如果這個值是一個對象,則會通過 webpack-merge 合並到最終的配置中。
   * 如果這個值是一個函數,則會接收被解析的配置作為參數。
   * 該函數及可以修改配置並不返回任何東西,也可以返回一個被克隆或合並過的配置版本。
   * */
  configureWebpack: {

    plugins: [
      // webpack-bundle-analyzer 是否使用可視化打包分析
      /*     new BundleAnalyzerPlugin({
               analyzerMode: 'static',
               analyzerPort: 8091, // 運行后的端口號 可以修改
               generateStatsFile: true,
               statsOptions: {source: false}
           })*/
    ],

    // 別名配置
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src'),
        'assets': path.resolve(__dirname, './src/assets/images'),
        'api': path.resolve(__dirname, './src/api'),
      }
    },
  },

  /**
   * devServer:所有 webpack-dev-server 的選項都支持。
   * 當設置為 `"error"` 時,檢查出的錯誤會觸發編譯失敗。
   * */
  devServer: {
    port: 8080, // 端口
    https: false, // 啟用https
    // proxy:如果你的前端應用和后端 API 服務器沒有運行在同一個主機上,你需要在開發環境下將 API 請求代理到 API 服務器。
    proxy: {
      '/api': {
        target: `http://118.25.80.211:8080/`,
        changeOrigin: true, // 允許跨域
        ws: true,
        pathRewrite: {
          '^/api': '/'
        }
      }
    }
  },
};

 

九、頁面根目錄結構與封裝

  • 頁面結構
 


免責聲明!

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



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