1. 程式人生 > 其它 >使用vue-cli和element-ui快速搭建後臺管理系統

使用vue-cli和element-ui快速搭建後臺管理系統

技術標籤:前端微前端qiankunvueelementui

使用vue-cli和element-ui入門實踐

1. 環境配置

安裝node

從Node官網下載對應平臺的安裝程式https://nodejs.org/en/

在window上安裝時要注意:選擇全部元件,包括勾選Add to Path。

安裝完成後,在window環境下,開啟命令列視窗,然後輸入node -v,如果安裝正常,可以看到輸出如圖所示:
在這裡插入圖片描述

2. 安裝vue-cli

參考文件https://cli.vuejs.org/zh/

npm install -g @vue/cli

目前按照這種方式安裝應該是Vue CLI 4.X(需要Node.jsV8.9或更高版本)

2.1 檢視Vue cli的所有版本號

vue-cli3.X 和vue-cli4.x所有版本號檢視

npm view @vue/cli versions --json

vue-cli1.x和vue-cli2.x的所有版本號檢視

npm view vue-cli versions --json

2.2 安裝指定版本號的vue-cli

安裝3.x和4.x版本(推薦安裝這兩個版本)

npm install -g @vue/[email protected]版本號

安裝1.x和2.x版本

npm install -g [email protected]版本號

安裝完成後,命令列執行vue -V

,正常輸出版本號,則說明安裝成功。

3. 專案搭建

3.1 建立一個vue-cli3專案

vue create mmp-subapp1

mmp-subapp1為自定義專案名稱,回車之後依次選預設的即可

3.2 使用element-ui元件

  1. 安裝element-ui依賴

    npm install element-ui
    
  2. 安裝sass和sass-loader ,因為element-ui中的樣式預設是使用sass來編寫的

    npm install sass --save-dev
    npm install sass-loader --save-dev
    
  3. 在main.js檔案中引入element-ui和樣式,新增以下程式碼即可

    import ElementUI from 'element-ui'; //引入ElementUI
    import 'element-ui/lib/theme-chalk/index.css' //引入element-ui樣式
    
    Vue.use(ElementUI)
    
  4. 使用elment-ui元件

    1. 例如在App.vue中:

      <template>
        <div id="app">
          <!-- 全域性引入的element-ui的元件 -->
          <el-button>按鈕元件</el-button>
        </div>
      </template>
      
      <script>
      export default {
        name: 'App'
      }
      </script>
      
      <style>
      #app {
        font-family: Avenir, Helvetica, Arial, sans-serif;
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
        color: #2c3e50;
      }
      </style>
      
    2. 頁面效果

      [外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片儲存下來直接上傳(img-PYbbGpbq-1610618885917)(file://D:/Users/dandanhu/AppData/Roaming/Typora/typora-user-images/image-20201214203157993.png?lastModify=1607949117)]

3.3 使用自定義元件(以header元件為例)

  1. components資料夾中新增如下結構檔案

在這裡插入圖片描述

  1. Index.vue檔案中新增頭部元件的內容如下

    <template>
        <div class="base-header">
            <div class="base-header-logo">
                <img src="../../assets/logo.png"/><span >支付模組管理平臺</span>
            </div>
            <div class="base-header-userInfo">
                <div class="base-header-userName">{{userName}}</div>
                <span class="base-header-logout-btn" @click="logout">退出登入</span>
            </div> 
        </div>
    </template>
    
    <script>
    export default {
        name:'CusHeader',
        data() {
            return {
                userName: '韋小寶' //要顯示的使用者名稱稱
            }
        },
        methods: {
            logout() {
                //退出登入操作
                console.log('退出登入')
            }
        },
    }
    </script>
    
    <style lang="scss" scoped>
    .base-header {
        background-color:#001529;
        height:calc(5vh);
        color:#fff;
        .base-header-logo {
            margin-left:10px;
            display: inline-block;
            img {
            display: inline-block;
            width: 2.8em;
            height: 2.8em;
            vertical-align: middle;
            }
            span {
                font-size:1.5em;
                display: inline-block;
                vertical-align: middle;
            }
        }
        .base-header-userInfo {
            float: right;
            height: 100%;
            line-height: 2.8em;
            margin-right: 20px;
            .base-header-userName {
                display: inline-block;
                margin-right: 10px;
            }
            .base-header-logout-btn {
                display: inline-block;
                cursor: pointer;
                font-size:1.2em;
                font-weight: 700;
                margin-right: 10px;
            }
        }
    }
    
    </style>
    
  2. App.vue中使用元件

    <template>
      <div id="app">
        <!-- 全域性引入的element-ui的元件 -->
        <el-button>按鈕元件</el-button>
        <!-- 自定義元件 -->
        <cus-header></cus-header>
      </div>
    </template>
    
    <script>
    
    import CusHeader from '@/components/Header/Index.vue'
    export default {
      name: 'App',
      components: {
        CusHeader
      }
    }
    </script>
    
    <style>
    #app {
      font-family: Avenir, Helvetica, Arial, sans-serif;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
      color: #2c3e50;
    }
    </style>
    

3.4 帶路由功能的導航選單元件

  1. 安裝vue-router依賴(官方文件:https://router.vuejs.org/zh/)

    npm install --save vue-router
    
  2. src資料夾下新增頁面檔案

在這裡插入圖片描述

以View1.vue為例,檔案新增的內容為:

<template>
    <div>
        這是View111111111
    </div>
</template>

<script>
    export default {
        
    }
</script>

<style lang="scss" scoped>

</style>
  1. src資料夾下新增如下結構檔案,並新增路由配置

在這裡插入圖片描述

index.js

const routes = [
    {
      /**
       * path: 路徑為 / 時觸發該路由規則
       * name: 路由的 name 為 Home
       * component: 觸發路由時載入 `Home` 元件
       */
      path: "/View1",
      name: "View1",
      component: resolve => require(['../views/View1.vue'], resolve),
    },
    {
      path: "/View2",
      name: "View2",
      component: resolve => require(['../views/View2.vue'], resolve),
    },
    {
      path: "/View3",
      name: "View3",
      component: resolve => require(['../views/View3.vue'], resolve),
    }
  ];
  
  export default routes;

新增Vue Router,其實就是將元件 (components) 對映到路由 (routes),然後告訴 Vue Router 在哪裡渲染它們

  1. main.js引入vue-router並使用

    import Vue from 'vue'
    import App from './App.vue'
    //引入UI元件
    import ElementUI from 'element-ui';
    import 'element-ui/lib/theme-chalk/index.css'
    // 引入路由
    import VueRouter from 'vue-router'
    import routes from './router'
    
    
    Vue.config.productionTip = false
    Vue.use(ElementUI)
    
    Vue.use(VueRouter)
    
    const router = new VueRouter({
      mode: "history",
      routes,
    })
    
    
    new Vue({
      router,
      render: h => h(App),
    }).$mount('#app')
    

    通過注入路由器,我們可以在任何元件內通過 this.$router 訪問路由器,也可以通過 this.$route 訪問當前路由

  2. components資料夾下面新增menu元件,結構如圖

    在這裡插入圖片描述

    Index.vue

    <template>
        <div>
            <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect" router>
                <template v-for="item in menuData" >
                    <el-submenu v-if='item.children' :index="item.index" :key="item.index">
                        <template slot="title">
                            <i :class="item.icon"></i>
                            <span>{{item.name}}</span>
                        </template>
                        <el-menu-item-group>
                            <el-menu-item v-for="subItem in item.children" :index="subItem.index" :key="subItem.index">{{subItem.name}}</el-menu-item>
                        </el-menu-item-group>
                    </el-submenu>
                    <el-menu-item v-else :index="item.index" :key="item.index">
                        <i :class="item.icon"></i>
                        <span slot="title">{{item.name}}</span>
                    </el-menu-item>
                </template>
            </el-menu>
        </div>
    </template>
    
    <script>
        export default {
            name:'CusHorizMenu',
            props:{
                menuData:{
                    type:Array,
                    default(){
                        return[]
                    }
                }
            },
            data() {
                return {
                    activeIndex: 'View1'
                }
            },
            methods: {
                handleSelect() {
                    console.log('選中導航選單的時候觸發') 
                }
            },
            
        }
    </script>
    
    <style lang="scss" scoped>
    
    </style>
    

    更多el-menu相關配置見官方文件(https://element.eleme.cn/#/zh-CN/component/menu)

  3. App.vue檔案中引入選單元件,並定義選單欄資料menuData

    <template>
      <div id="app">
        <!-- 全域性引入的element-ui的元件 -->
        <el-button>按鈕元件</el-button>
        <!-- 自定義元件 -->
        <cus-header></cus-header>
        <!-- 帶路由的自定義元件(內部是element-ui元件)-->
        <horiz-menu :menuData="menuData"></horiz-menu>
        <!-- 路由元件內容展示區 -->
        <router-view></router-view>
      </div>
    </template>
    
    <script>
    
    import CusHeader from '@/components/Header/Index.vue'
    import HorizMenu from '@/components/HorizMenu/Index.vue'
    export default {
      name: 'App',
      components: {
        CusHeader,
        HorizMenu
      },
      data() {
        return {
          menuData: [
            {
              index:'View1',
              name:'View1頁',
              icon:'el-icon-location',
            },
            {
              index:'View2',
              name:'View2頁',
              icon:'el-icon-location',
            },
            {
              index:'View3',
              name:'View3頁',
              icon:'el-icon-location',
            }
          ]
        }
      },
    }
    </script>
    
    <style>
    #app {
      font-family: Avenir, Helvetica, Arial, sans-serif;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
      color: #2c3e50;
    }
    </style>
    
    

3.5 路由跳轉

  1. 普通跳轉

    使用 <router-link> 標籤 建立 a 標籤來定義導航連結

    View1.vue

    <template>
        <div>
            這是View111111111
            <h1>使用 router-link 標籤 建立 a 標籤來定義導航連結</h1>
            <router-link to="/View2">Go to Foo</router-link>
        </div>
    </template>
    
    <script>
        export default {
            name:'View1'
        }
    </script>
    
    <style lang="scss" scoped>
    
    </style>
    

    常用的程式設計式導航

    View2.vue

    <template>
        <div>
            這是View22222222222
            <h2>程式設計式導航</h2>
            <el-button @click="toView3">跳轉到View3頁面</el-button>
            <h3>程式設計式導航的兩種帶引數跳轉</h3>
            <div>
                <el-button @click="toView3Param">帶引數跳轉到View3頁面name和params組合</el-button>
                <el-button @click="toView3Query">帶引數跳轉到View3頁面path和query組合</el-button>
            </div>
        </div>
    </template>
    
    <script>
        export default {
            name:'View2',
            methods: {
                toView3() {
                    this.$router.push('View3')
                    // this.$router.push({path:'View3'})
                },
                toView3Param() {
                    this.$router.push({ name: 'View3', params: { userId: '位址列看不見的引數' }})
                },
                toView3Query() {
                    this.$router.push({ path: '/View3', query: { userId: '位址列看得見的引數' }})
                }
            },
            
        }
    </script>
    
    <style lang="scss" scoped>
    
    </style>
    

    導航守衛–元件內的導航守衛

    View3

    <template>
        <div>
            這是View33333333333
            <div>接收到從View2帶來的引數</div>
            <div>param={{param}}</div>
            <div>query={{query}}</div>
        </div>
    </template>
    
    <script>
        export default {
            name:'View3',
            data() {
                return {
                    param:'',
                    query:''
                }
            },
            beforeRouteEnter(to, from, next) {
                //to, 即將要進入的目標路由物件
                //from, 當前導航正要離開的路由
                //next() 進行管道中的下一個鉤子,如果鉤子全部執行完了,則導航的狀態就是comfirmed
                // 在渲染該元件的對應路由被 confirm 前呼叫
                // 不!能!獲取元件例項 `this`
                // 因為當守衛執行前,元件例項還沒被建立
                console.log(to, from, next)
                //next必須寫,否則跳轉不會成功,通過 `vm` 訪問元件例項
                next(vm=>{
                    vm.param = to.params.userId ? to.params.userId : ''
                    vm.query = to.query.userId ? to.query.userId : ''
                })
            },
            beforeRouteUpdate (to, from, next) {
                console.log(to, from, next)
                // 在當前路由改變,但是該元件被複用時呼叫
                // 舉例來說,對於一個帶有動態引數的路徑 /foo/:id,在 /foo/1 和 /foo/2 之間跳轉的時候,
                // 由於會渲染同樣的 Foo 元件,因此元件例項會被複用。而這個鉤子就會在這個情況下被呼叫。
                // 可以訪問元件例項 `this`
            },
            beforeRouteLeave (to, from, next) {
                console.log(to, from, next)
                // 導航離開該元件的對應路由時呼叫
                // 可以訪問元件例項 `this`
            }
        }
    </script>
    
    <style lang="scss" scoped>
    
    </style>
    

    導航守衛參考(https://router.vuejs.org/zh/guide/advanced/navigation-guards.html#%E5%85%A8%E5%B1%80%E5%89%8D%E7%BD%AE%E5%AE%88%E5%8D%AB

3.6 新增配置

資料夾根目錄位置新增vue.config.js

常用的幾個:

module.exports = {
	publicPath:'',//部署應用包時的基本 URL,如果你的應用被部署在 https://www.my-app.com/my-app/,則設定 publicPath 為 /my-app/
	outputDir:'', //生成的生產環境構建檔案的目錄 buil時使用,目標目錄在構建之前會被清除 (構建時傳入 --no-clean 可關閉該行為)。
	assetsDir:'',//放置生成的靜態資源 (js、css、img、fonts) 的 (相對於 outputDir 的) 目錄,相對地址
    devServer: {
      port: 10001, //指定啟動專案所用的埠號
    //   proxy: 'localhost:8080', //代理地址,你的前端應用和後端 API 伺服器沒有執行在同一個主機上,你需要在開發環境下將 API 請求代理到 API 伺服器
    //   open: true,
    //   // 關閉主機檢查,使微應用可以被 fetch
    //   disableHostCheck: true,
    //   // 配置跨域請求頭,解決開發環境的跨域問題
    //   headers: {
    //     'Access-Control-Allow-Origin': '*',
    //   },
    }
}

具體的各項配置含義:https://cli.vuejs.org/zh/config/#vue-config-js