vue-element-template實現(xiàn)權(quán)限管理钝凶、動態(tài)路由、動態(tài)加載側(cè)邊欄

api地址:https://www.showdoc.com.cn/aoaoe?page_id=5696507784013382
這些字段做項目時候需要跟后端說這幾個字段是必須的唁影。

頂部是一級菜單耕陷,側(cè)邊是二級菜單參考鏈接:http://www.reibang.com/p/44a9511bda9a

image.png

1.首先下載該模板https://gitee.com/PanJiaChen/vue-admin-template

├── build                      # 構(gòu)建相關(guān)1
├── mock                       # 項目mock 模擬數(shù)據(jù)
├── public                     # 靜態(tài)資源
│   │── favicon.ico            # favicon圖標(biāo)
│   └── index.html             # html模板
├── src                        # 源代碼
│   ├── api                    # 所有請求
│   ├── assets                 # 主題 字體等靜態(tài)資源
│   ├── components             # 全局公用組件
│   ├── icons                  # 項目所有 svg icons
│   ├── layout                 # 全局 layout
│   ├── router                 # 路由
│   ├── store                  # 全局 store管理
│   ├── styles                 # 全局樣式
│   ├── utils                  # 全局公用方法
│   ├── views                  # views 所有頁面
│   ├── App.vue                # 入口頁面
│   ├── main.js                # 入口文件 加載組件 初始化等
│   └── permission.js          # 權(quán)限管理
├── tests                      # 測試
├── .env.xxx                   # 環(huán)境變量配置
├── .eslintrc.js               # eslint 配置項
├── .babelrc                   # babel-loader 配置
├── .travis.yml                # 自動化CI配置
├── vue.config.js              # vue-cli 配置
├── postcss.config.js          # postcss 配置
└── package.json               # package.json

2.下載好了以后,打開vue.config.js文件注釋掉before: require('./mock/mock-server.js'),關(guān)閉eslint


image.png

image.png

3.打開router文件夾下的index.js据沈,刪除多余的路由哟沫,改成這樣

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

Vue.use(Router)

/* Layout */
import Layout from '@/layout'

/**
 * Note: sub-menu only appear when route children.length >= 1
 * Detail see: https://panjiachen.github.io/vue-element-admin-site/guide/essentials/router-and-nav.html
 *
 * hidden: true                   if set true, item will not show in the sidebar(default is false)
 * alwaysShow: true               if set true, will always show the root menu
 *                                if not set alwaysShow, when item has more than one children route,
 *                                it will becomes nested mode, otherwise not show the root menu
 * redirect: noRedirect           if set noRedirect will no redirect in the breadcrumb
 * name:'router-name'             the name is used by <keep-alive> (must set!!!)
 * meta : {
    roles: ['admin','editor']    control the page roles (you can set multiple roles)
    title: 'title'               the name show in sidebar and breadcrumb (recommend set)
    icon: 'svg-name'/'el-icon-x' the icon show in the sidebar
    breadcrumb: false            if set false, the item will hidden in breadcrumb(default is true)
    activeMenu: '/example/list'  if set path, the sidebar will highlight the path you set
  }
 */

/**
 * constantRoutes
 * a base page that does not have permission requirements
 * all roles can be accessed
 */
export const constantRoutes = [{
        path: '/login',
        component: () => import('@/views/login/index'),
        hidden: true
    },


    {
        path: '/',
        component: Layout,
        redirect: '/dashboard',
        children: [{
            path: 'dashboard',
            name: 'Dashboard',
            component: () => import('@/views/dashboard/index'),
            meta: { title: 'Dashboard', icon: 'dashboard' }
        }]
    },
]

const createRouter = () => new Router({
    // mode: 'history', // require service support
    scrollBehavior: () => ({ y: 0 }),
    routes: constantRoutes
})

const router = createRouter()

// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
    const newRouter = createRouter()
    router.matcher = newRouter.matcher // reset router
}

export default router

4.刪除views文件夾內(nèi)的form、nested锌介、table嗜诀、tree文件夾,清空api文件夾內(nèi)的文件孔祸,新建index.js

5.修改store/modules/user.js內(nèi)的import { login, logout, getInfo } from '@/api/user',user改成index


image.png

6.在vue.config.js配置反向代理


image.png
proxy: {
            //配置跨域
            '/api': {
                target: "http://localhost:8888", //測試服接口地址
                ws: true,
                changOrigin: true,
                pathRewrite: {
                    '^/api': ''
                }
            }
        }

7.然后在.env.deveplopment文件內(nèi) VUE_APP_BASE_API = '/dev-api'改成VUE_APP_BASE_API = '/api',然后隆敢,重啟項目,否則不生效


image.png

8.在api/index.js內(nèi)把登錄接口和獲取用戶詳情和獲取動態(tài)路由(側(cè)邊欄)接口配置好

import request from '@/utils/request'
//登錄接口
export function login(data) {
    return request({
        url: '/admin/api/login',
        method: 'post',
        data
    })
}
// 獲取用戶詳情
export function getInfo(data) {
    return request({
        url: '/admin/api/boss/detail',
        method: 'post',
        data
    })
}
// 動態(tài)路由
export function DongtRouter() {
    return request({
        url: `/aoaoe/api/getMoveRouter`,
        method: 'get',
    })
}


9.修改store/modules/user.js內(nèi)的import { login, logout, getInfo } from '@/api/index' 改成 import { login, DongtRouter, getInfo } from '@/api/index'

10.修改src/utils/request.js中的config.headers['X-Token'] = getToken(),把 X-Token改成后端需要的key值崔慧,這里根據(jù)實際情況需要改成token拂蝎,config.headers['token'] = getToken()


image.png

if (res.code !== 200) {
            Message({
                message: res.message || 'Error',
                type: 'error',
                duration: 5 * 1000
            })

            // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
            if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
                // to re-login
                MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
                    confirmButtonText: 'Re-Login',
                    cancelButtonText: 'Cancel',
                    type: 'warning'
                }).then(() => {
                    store.dispatch('user/resetToken').then(() => {
                        location.reload()
                    })
                })
            }
            return Promise.reject(new Error(res.message || 'Error'))
        } else {
            return res
        }

上面??這段代碼,根據(jù)實際情況改惶室,主要就是修改code值温自,如果,后端返回的code成功狀態(tài)值是200皇钞,那么這里就改成200悼泌。if (res.code === 50008 || res.code === 50012 || res.code === 50014)這里也根據(jù)后端返回的code按照實際情況來改,目前我沒有動夹界。

image.png

重點部分:開始了9堇铩!可柿!

11.接下來也拜,打開views/login/index.vue,注釋掉loginRules內(nèi)的校驗趾痘,你也可以根據(jù)實際情況來自定義校驗,我懶省事蔓钟,直接注釋掉了


image.png

12.這時候打開項目永票,點擊登錄,提示該用戶不存在,注意侣集,本模版默認(rèn)傳給后端的是key值是username键俱、password,而后端要求的key是loginame世分、password编振,把loginForm對象內(nèi)的username改成loginame,

<el-input ref="username" v-model="loginForm.username" placeholder="Username" name="username" type="text" tabindex="1" auto-complete="on" />

改成

<el-input ref="username" v-model="loginForm.loginame" placeholder="Username" name="username" type="text" tabindex="1" auto-complete="on" />

在需要修改store/modules/user.js臭埋,把actions中的login方法修改成下面這樣:

  // user login
  login({ commit }, userInfo) {
    const { loginame, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ loginame: loginame.trim(), password: password }).then(response => {
        commit('SET_TOKEN', response.token)
        setToken(response.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
image.png

13.這時候打開項目踪央,點擊登錄,提示賬號密碼錯誤瓢阴,說明接口已經(jīng)跑通畅蹂。


image.png

14.我們輸入正確的賬號密碼 admin 123456 ,點擊登錄,登錄成功是這樣的


image.png

可以看到荣恐,因為還沒請求獲取動態(tài)路由的接口液斜,所以側(cè)邊欄是空的,頭像也是裂的叠穆,下面我們就來解決這些問題少漆。

15.頭像裂是因為,我們還沒請求用戶信息硼被,現(xiàn)在來操作
首先打開store/modules/user.js,把getInfo這個方法改造成這樣:(因為后臺我沒設(shè)計頭像示损,存?zhèn)€死值,各位老表自己根據(jù)自己后端實際返回的來存)


image.png

然后祷嘶,頭像就正常了

16.下面做渲染側(cè)邊欄屎媳,請求動態(tài)路由,請求接口之前论巍,要先做一些配置:
(1)先在router這個目錄下新建兩個js文件烛谊,開發(fā)環(huán)境和生產(chǎn)環(huán)境導(dǎo)入組件的方式略有不同
_import_development.js

// 開發(fā)環(huán)境導(dǎo)入組件
module.exports = file => require('@/views/' + file + '.vue').default // vue-loader at least v13.0.0+

_import_production.js

// 生產(chǎn)環(huán)境導(dǎo)入組件
module.exports = file => () => import('@/views/' + file + '.vue')
image.png

(2)在src/permission.js中引入文件

import Layout from "@/layout";
const _import = require('./router/_import_' + process.env.NODE_ENV) // 獲取組件的方法
image.png

(3)在await store.dispatch('user/getInfo')下面寫這段代碼


image.png

(4)在最底部新寫一個方法


image.png

這時候點擊登錄,報錯嘉汰,別著急丹禀。繼續(xù)往下走


image.png

(5)打開store/modules/user.js,在actions中新建一個方法,請求路由表


image.png

(6)在getDefaultState中鞋怀,新增menus: "",mutations中新增 SET_MENUS: (state, menus) => { state.menus = menus }


image.png

(7)在getters.js中新增 menus: state => state.user.menus


image.png

這時候點擊登錄双泪,會報這個錯:


image.png

意思就是找不到vue文件,根據(jù)實際情況密似,新建文件:
(8)在views下新建:system文件夾焙矛,文件夾內(nèi)新建三個文件夾,分別是 menu 残腌、 roles 村斟、user 贫导,三個文件夾下分別新建index.vue
這時候在點擊登錄,不報錯蟆盹,進(jìn)來了孩灯,但是側(cè)邊欄還是沒東西,還差一步:
(9)打開layout/components/Sidebar/index.vue逾滥,計算屬性中峰档,把routes改成


image.png

這時候在刷新頁面,完美展示:


image.png

17.下面準(zhǔn)備開始開發(fā)菜單管理頁面寨昙。老規(guī)矩讥巡,先把接口地址配置好。
在api文件夾下毅待,新建system文件夾尚卫,內(nèi)新建index.js,
里面這樣寫:

import request from '@/utils/request'
// 獲取菜單列表接口
export function getMenuList(params) {
    return request({
      url: '/aoaoe/api/getMenuList',
      method: 'get',
      params
    })
  }
// 新增菜單
  export function addMenu(data) {
    return request({
      url: '/aoaoe/api/menu/add',
      method: 'post',
      data
    })
  }
// 修改菜單
export function updateMenu(id,data) {
    return request({
      url: `/aoaoe/api/menu/update/${id}`,
      method: 'put',
      data
    })
  }

 // 刪除菜單
export function delMenu(id) {
    return request({
      url: `/aoaoe/api/menu/delete/${id}`,
      method: 'delete',
    })
  }

image.png

把紅圈中的封裝成一個組件尸红,方便復(fù)用

在components/System下新建一個Toobar.vue文件吱涉,里面這樣寫:

<template>
  <div>
    <!--工具欄-->
    <div class="head_container">
      <span>
        <el-input
          class="filter-item"
          v-model="searchKey"
          clearable
          placeholder="請輸入內(nèi)容"
          style="width: 200px"
          @keyup.enter.native="toQuery"
        ></el-input>
        <span class="filter-item">
          <el-button type="success" icon="el-icon-search">搜索</el-button>
          <el-button type="warning" icon="el-icon-refresh-left">重置</el-button>
          <el-button type="primary" icon="el-icon-plus" @click="Add" v-permission="AddBtnAuth">新增</el-button>
        </span>
      </span>
      <span>
        <el-button-group>
          <el-button icon="el-icon-search"></el-button>
            <el-button icon="el-icon-refresh"></el-button>
        </el-button-group>
      </span>
    </div>
  </div>
</template>

<script>
export default {
  props:["AddBtnAuth"],
  data() {
    return {
      searchKey: "",
    };
  },
  methods: {
    toQuery() {},
    Add(){
      this.$emit("handleAdd")
    },
  },
};
</script>

<style lang="scss" scoped>
.head_container{
  display: flex;
  align-items: center;
  justify-content: space-between;
  span{
    display: flex;
     align-items: center;
  }
  .filter-item{
    margin-left:10px;
  }
}
</style>


props: { AddBtnAuth: { type: Array, }, },這段代碼是接收的父組件傳過來的添加按鈕權(quán)限,后面會講到

在main.js內(nèi)引入外里,讓其成為全局組件

Vue.component('toolbar', () => import('@/components/System/toolbar.vue'))

在menu/index.vue內(nèi)使用怎爵,出現(xiàn)說明成功,但是太大了盅蝗,在main.js配置

import Cookies from 'js-cookie'
Vue.use(ElementUI, {size: Cookies.get('size') || 'mini' // set element-ui default size})

這樣就好了

18.在components下新建System/menu/dialogMenu.vue;
里面暫時這樣寫:

<template>
  <div>
    <el-dialog :title="dialogMenu.title" :visible.sync="dialogMenu.show" width="40%">
      <el-form ref="form" :rules="rules" :model="formData" label-width="80px">
        <!--菜單類型-->
        <el-form-item label="菜單類型">
          <el-radio-group v-model="formData.type">
            <el-radio-button label="1" :disabled="formData.type != '1' && dialogMenu.option == 'edit'">目錄</el-radio-button>
            <el-radio-button label="2" :disabled="formData.type != '2' && dialogMenu.option == 'edit'">菜單</el-radio-button>
            <el-radio-button label="3" :disabled="formData.type != '3' && dialogMenu.option == 'edit'">按鈕</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <!--選擇圖標(biāo)-->
        <el-form-item label="選擇圖標(biāo)" v-if="formData.type != 3" prop="icon">
          <e-icon-picker v-model="formData.icon" :options="options" style="width: 76%"></e-icon-picker>
        </el-form-item>
        <!--是否可見鳖链,菜單標(biāo)題-->
        <div class="flex" style="display: flex" v-if="formData.type != 3">
          <el-form-item label="是否可見">
            <el-radio-group v-model="formData.hidden">
              <el-radio-button label="1">是</el-radio-button>
              <el-radio-button label="0">否</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="目錄標(biāo)題" style="margin-left: 10px" prop="title">
            <el-input v-model="formData.title" placeholder="請輸入標(biāo)題"></el-input>
          </el-form-item>
        </div>
        <!--路由地址和菜單排序-->
        <div class="flex" style="display: flex" v-if="formData.type != 3">
          <el-form-item label="路由地址" prop="path">
            <el-input v-model="formData.path" placeholder="路由地址(/:path)"></el-input>
          </el-form-item>
          <el-form-item label="菜單排序" style="margin-left: 10px" prop="sort">
            <el-input-number v-model="formData.sort" controls-position="right" placeholder="請排序"></el-input-number>
          </el-form-item>
        </div>
        <!--組件名稱、組件路徑-->
        <div class="flex" style="display: flex" v-if="formData.type == 2">
          <el-form-item label="組件名稱" prop="name">
            <el-input v-model="formData.name" placeholder="請輸入組件name"></el-input>
          </el-form-item>
          <el-form-item label="組件路徑" style="margin-left: 15px" prop="component">
            <el-input placeholder="請輸入組件路徑" @input="change($event)" v-model="formData.component"></el-input>
          </el-form-item>
        </div>
        <!-- 按鈕名稱墩莫、權(quán)限標(biāo)識 -->
        <div class="flex" style="display: flex" v-if="formData.type == 3">
          <el-form-item label="按鈕名稱" prop="title">
            <el-input placeholder="請輸入按鈕名稱" v-model="formData.title"></el-input>
          </el-form-item>
          <el-form-item label="權(quán)限標(biāo)識" style="margin-left: 15px" prop="permissions">
            <el-input placeholder="請輸入權(quán)限標(biāo)識" v-model="formData.permissions"></el-input>
          </el-form-item>
        </div>
        <!--上級類目-->
        <div class="flex" style="display: flex">
          <el-form-item label="上級類目" prop="pid">
            <el-cascader :options="allMenu" v-model="formData.pid" placeholder="請選擇" :props="{ checkStrictly: true, label: 'title', value: '_id' }" :show-all-levels="false" clearable></el-cascader>
          </el-form-item>
          <el-form-item label="按鈕排序" style="margin-left: 10px" prop="sort" v-if="formData.type == 3">
            <el-input-number v-model="formData.sort" controls-position="right" placeholder="請排序"></el-input-number>
          </el-form-item>
        </div>
      </el-form>
      {{this.formData}}
      <span slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="handleSubmit('form')">確 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { getMoveRouter } from "@/api/index";
export default {
  props: {
    dialogMenu: Object,
    formData: Object,
  },
  data () {
    return {
      allMenu: [], //全部的路由
      nest: "0",//默認(rèn)是0芙委,不是嵌套路由

      options: {
        FontAwesome: false,
        ElementUI: true,
        eIcon: false, //自帶的圖標(biāo),來自阿里媽媽
        eIconSymbol: false, //是否開啟彩色圖標(biāo)
        addIconList: [],
        removeIconList: [],
      },
      rules: {
        title: [{ required: true, message: "請輸入標(biāo)題", trigger: "blur" }],
        icon: [{ required: true, message: "請選擇圖標(biāo)", trigger: "blur" }],
        sort: [{ required: true, message: "請輸入排序編號", trigger: "blur" }],
        name: [{ required: true, message: "請輸入組件name", trigger: "blur" }],
        path: [{ required: true, message: "請輸入組件路徑", trigger: "blur" }],
        icon: [{ required: true, message: "請選擇圖標(biāo)", trigger: "change" }],
        pid: [{ required: true, message: "請選擇上級類目", trigger: "change" }],
        component: [
          { required: true, message: "請輸入組件路徑", trigger: "blur" },
        ],
        permissions: [
          { required: true, message: "請輸入權(quán)限標(biāo)識", trigger: "blur" },
        ],
      },
    };
  },
  created () {
    this.init();
  },
  watch: {
    "formData.type": {
      handler: function () {
        if (this.formData.type == "1") {
          this.formData.redirect = "noRedirect"; //建議 必須是 ‘noRedirect’,因為如果是redirect的話面包屑那一塊是可以點擊跳轉(zhuǎn)狂秦,這樣做沒有意義
          this.formData.alwaysShow = "1"; //設(shè)置成1 意思是總是顯示父級灌侣,-----如果沒這個字段或者這個字段為0 意思就是當(dāng)只有一個子菜單的時候,不顯示父級
          this.formData.component = "Layout"; //必須是 Layout
          this.nest = "0";
        } else {
          this.formData.redirect = "";
          this.formData.alwaysShow = "";
          if (this.dialogMenu.option == "add") {
            this.formData.component = "";
          }
        }
        if (this.formData.type == "3") {
          this.nest = "0";
        }
      },
      immediate: true,
    },
    //監(jiān)聽nest路由嵌套
    "nest": {
      handler: function () {
        if (this.nest == "1") {
          this.formData.redirect = "noRedirect";
          this.formData.alwaysShow = "1"
        } else {
          this.formData.redirect = "";
          this.formData.alwaysShow = ""
        }
      }
    }
  },
  methods: {
    close () {
      this.$emit("close");
    },
    init () {
      getMoveRouter().then((res) => {
        if (this.formData.type == 1) {
          res.data.push({
            _id: "0",
            title: "頂級目錄",
          });
        }
        this.allMenu = res.data;
        if (this.dialogMenu.option == "edit") {
          if (this.formData.type == 2) {
            res.data.forEach((item) => {
              if (item.children) {
                item.children.forEach((ele) => {
                  ele.disabled = true;
                });
              }
            });
          }
        }
      });
    },
    //點擊確定按鈕提交
    handleSubmit (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialogMenu.option == "add") {
            this.formData.pid = this.formData.pid[this.formData.pid.length - 1];
            this.$emit("handleSubmit");
            this.$emit("close");
          } else {
            if (typeof (this.formData.pid) != 'string') {
              this.formData.pid = this.formData.pid[this.formData.pid.length - 1];
            }
            this.$emit("handleSubmitEdit");

          }
        } else {
          return false;
        }
      });
    },
    //change
    change (e) {
      this.$forceUpdate();
    },
  },
};
</script>

<style lang="sass" scoped>
</style>

19.views/system/menu/index.vue里這樣寫:

<template>
  <div class="main" style="margin: 10px">
    <el-card>
      <!--頭部組件-->
      <Toobar :AddBtnAuth="AddBtnAuth" @handleAdd="handleAdd"></Toobar>
    </el-card>
    <el-button @click="PrintRow" type="success">打印按鈕</el-button>
    <!--表格-->
    <el-card style="margin-top: 10px" ref="print">
      <el-table :data="tableData" v-loading="loading" style="width: 100%" row-key="_id" ref="table" lazy :load="getChildMenus" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">>
        <el-table-column type="index" label="#" align="center">
        </el-table-column>
        <el-table-column prop="title" label="菜單標(biāo)題" width="200">
        </el-table-column>
        <el-table-column prop="icon" label="圖標(biāo)" align="center">
        </el-table-column>
        <el-table-column prop="sort" label="排序" align="center">
        </el-table-column>
        <el-table-column prop="permissions" label="權(quán)限標(biāo)識" align="center">
          <template slot-scope="scope">
            {{ scope.row.permissions == "" ? "--" : scope.row.hidden }}
          </template>
        </el-table-column>
        <el-table-column prop="component" label="組件路徑" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.component == 'Layout'">--</span>
            <span v-else>{{
              scope.row.component == undefined ? "--" : scope.row.component
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="菜單類型" align="center">
          <template slot-scope="scope">
            <el-tag type="success" v-if="scope.row.type == 1">目錄</el-tag>
            <el-tag type="warning" v-if="scope.row.type == 2">菜單</el-tag>
            <el-tag type="danger" v-if="scope.row.type == 3">按鈕</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="hidden" label="是否可見" align="center">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.hidden" active-color="#13ce66" inactive-color="#ff4949" active-text="是" active-value="1" inactive-text="否" inactive-value="0" disabled>
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="創(chuàng)建日期" align="center" width="200">
          <template slot-scope="scope">
            {{ scope.row.date | formatDate }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">編輯</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">刪除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <div style="height:100000px"></div>
    <!--彈窗組件-->
    <dialog-menu ref="haode" v-if="dialogMenu.show" :dialogMenu="dialogMenu" :formData="formData" @handleSubmit="handleSubmit" @handleSubmitEdit="handleSubmitEdit" @close="close"></dialog-menu>
  </div>
</template>

<script>
import Toobar from "@/components/System/Toobar";
import { getMenuList, delMenu, addMenu, updateMenu } from "@/api/system/index";
import DialogMenu from "@/components/System/menu/dialogMenu.vue";

export default {
  components: { Toobar, DialogMenu },
  data () {
    return {
      AddBtnAuth: ["add"],
      tableData: [],
      dialogMenu: {
        //定義彈窗是否顯示屬性
        show: false,
        title: "新增菜單",
        option: "add",
      },
      formData: {},
      oldPid: "",
      loading: true
    };
  },
  created () {
    this.init();
  },
  methods: {
    init () {
      console.log("init觸發(fā)")
      console.log(this.$refs)
      getMenuList({ pid: 0 }).then((res) => {
        if (res.code == 200) {
          this.tableData = res.data;
          this.loading = false;
        } else {
          this.tableData = [];
          this.loading = false
        }
      });
    },
    //getChildMenus獲取子菜單
    getChildMenus (tree, treeNode, resolve) {
      const data = { pid: tree._id };
      getMenuList(data).then((res) => {
        console.log(res);
        resolve(res.data);
      });
    },
    handleAdd () {
      this.dialogMenu = {
        show: true,
        title: "新增菜單",
        option: "add",
      };
      this.formData = {
        type: 1,
        hidden: 1,
        pid: "",
        icon: "",
        path: "",
        title: "",
        sort: "",
        name: "",
        component: "",
        permissions: "",
        noCache: "0",
      };

    },
    //提交新增請求
    handleSubmit (formData) {
      addMenu(this.formData).then((res) => {
        console.log(res);
        this.dialogMenu.show = false;
        this.$message.success("新增成功裂问!");
        if (this.formData.pid != 0) {
          // 實現(xiàn)無感刷新
          getMenuList({ pid: this.formData.pid }).then((res) => {
            this.$set(
              this.$refs.table.store.states.lazyTreeNodeMap,
              this.formData.pid,
              res.data
            );
          });
        } else {
          this.init();
        }
      });
    },
    //編輯請求
    handleSubmitEdit () {
      updateMenu(this.formData.id, this.formData).then((res) => {
        this.dialogMenu.show = false;
        this.$message.success("修改成功侧啼!");
        if (this.formData.pid != 0) {
          getMenuList({ pid: this.formData.pid }).then((res) => {
            this.$set(
              this.$refs.table.store.states.lazyTreeNodeMap,
              this.formData.pid,
              res.data
            );
          });
        } else {
          this.init();
        }
      });
    },
    //關(guān)閉新增菜單的彈窗
    close () {
      this.dialogMenu.show = false;
    },
    // 刪除按鈕觸發(fā)
    handleDelete (row) {
      console.log("點擊觸發(fā)")
      console.log(this.$refs)
      this.$confirm(
        "此操作將永久刪除該菜單,并刪除所屬子級, 是否繼續(xù)?",
        "提示",
        {
          confirmButtonText: "確定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          delMenu(row._id).then((res) => {
            this.$message({
              type: "success",
              message: "刪除成功!",
            });
            // 無感刷新
            getMenuList({ pid: row.pid }).then((res) => {
              this.$set(
                this.$refs.table.store.states.lazyTreeNodeMap,
                row.pid,
                res.data
              );
            });
            if (row.pid == 0) {
              this.init();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消刪除",
          });
        });
    },
    //編輯
    handleEdit (row) {

      this.dialogMenu = {
        show: true,
        title: "編輯菜單",
        option: "edit",
      };
      this.formData = {
        id: row._id,
        type: row.type,
        icon: row.icon,
        hidden: row.hidden,
        title: row.title,
        path: row.path,
        sort: row.sort,
        name: row.name,
        component: row.component,
        pid: row.pid + "",
        permissions: row.permissions,
        noCache: row.noCache == 0 ? "0" : "1",
      };
      this.oldPid = row.pid;
    },
    //打印
    PrintRow (index, row) {
      this.$print(this.$refs.print);
    }
    //打印結(jié)束
  },
};
</script>

<style>
</style>

20.因為用到e-icon-picker選擇圖標(biāo)的插件堪簿,所以要安裝下:


image.png

21.菜單就可以了痊乾。


image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請通過簡信或評論聯(lián)系作者椭更。
  • 序言:七十年代末哪审,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子虑瀑,更是在濱河造成了極大的恐慌协饲,老刑警劉巖畏腕,帶你破解...
    沈念sama閱讀 218,755評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異茉稠,居然都是意外死亡,警方通過查閱死者的電腦和手機把夸,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評論 3 395
  • 文/潘曉璐 我一進(jìn)店門而线,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人恋日,你說我怎么就攤上這事膀篮。” “怎么了岂膳?”我有些...
    開封第一講書人閱讀 165,138評論 0 355
  • 文/不壞的土叔 我叫張陵誓竿,是天一觀的道長。 經(jīng)常有香客問我谈截,道長筷屡,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,791評論 1 295
  • 正文 為了忘掉前任簸喂,我火速辦了婚禮毙死,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘喻鳄。我一直安慰自己扼倘,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,794評論 6 392
  • 文/花漫 我一把揭開白布除呵。 她就那樣靜靜地躺著再菊,像睡著了一般。 火紅的嫁衣襯著肌膚如雪颜曾。 梳的紋絲不亂的頭發(fā)上纠拔,一...
    開封第一講書人閱讀 51,631評論 1 305
  • 那天,我揣著相機與錄音泛啸,去河邊找鬼绿语。 笑死,一個胖子當(dāng)著我的面吹牛候址,可吹牛的內(nèi)容都是我干的吕粹。 我是一名探鬼主播,決...
    沈念sama閱讀 40,362評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼岗仑,長吁一口氣:“原來是場噩夢啊……” “哼匹耕!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起荠雕,我...
    開封第一講書人閱讀 39,264評論 0 276
  • 序言:老撾萬榮一對情侶失蹤稳其,失蹤者是張志新(化名)和其女友劉穎驶赏,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體既鞠,經(jīng)...
    沈念sama閱讀 45,724評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡煤傍,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了嘱蛋。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片蚯姆。...
    茶點故事閱讀 40,040評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖洒敏,靈堂內(nèi)的尸體忽然破棺而出龄恋,到底是詐尸還是另有隱情,我是刑警寧澤凶伙,帶...
    沈念sama閱讀 35,742評論 5 346
  • 正文 年R本政府宣布郭毕,位于F島的核電站,受9級特大地震影響函荣,放射性物質(zhì)發(fā)生泄漏显押。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,364評論 3 330
  • 文/蒙蒙 一偏竟、第九天 我趴在偏房一處隱蔽的房頂上張望煮落。 院中可真熱鬧,春花似錦踊谋、人聲如沸蝉仇。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽轿衔。三九已至,卻和暖如春睦疫,著一層夾襖步出監(jiān)牢的瞬間害驹,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評論 1 270
  • 我被黑心中介騙來泰國打工蛤育, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留宛官,地道東北人。 一個月前我還...
    沈念sama閱讀 48,247評論 3 371
  • 正文 我出身青樓瓦糕,卻偏偏與公主長得像底洗,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子咕娄,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,979評論 2 355

推薦閱讀更多精彩內(nèi)容