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

api地址:https://www.showdoc.com.cn/aoaoe?page_id=5696507784013382
這些字段做項(xiàng)目時(shí)候需要跟后端說(shuō)這幾個(gè)字段是必須的。

頂部是一級(jí)菜單,側(cè)邊是二級(jí)菜單參考鏈接:http://www.itdecent.cn/p/44a9511bda9a

image.png

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

├── build                      # 構(gòu)建相關(guān)1
├── mock                       # 項(xiàng)目mock 模擬數(shù)據(jù)
├── public                     # 靜態(tài)資源
│   │── favicon.ico            # favicon圖標(biāo)
│   └── index.html             # html模板
├── src                        # 源代碼
│   ├── api                    # 所有請(qǐng)求
│   ├── assets                 # 主題 字體等靜態(tài)資源
│   ├── components             # 全局公用組件
│   ├── icons                  # 項(xiàng)目所有 svg icons
│   ├── layout                 # 全局 layout
│   ├── router                 # 路由
│   ├── store                  # 全局 store管理
│   ├── styles                 # 全局樣式
│   ├── utils                  # 全局公用方法
│   ├── views                  # views 所有頁(yè)面
│   ├── App.vue                # 入口頁(yè)面
│   ├── main.js                # 入口文件 加載組件 初始化等
│   └── permission.js          # 權(quán)限管理
├── tests                      # 測(cè)試
├── .env.xxx                   # 環(huán)境變量配置
├── .eslintrc.js               # eslint 配置項(xiàng)
├── .babelrc                   # babel-loader 配置
├── .travis.yml                # 自動(dòng)化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", //測(cè)試服接口地址
                ws: true,
                changOrigin: true,
                pathRewrite: {
                    '^/api': ''
                }
            }
        }

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


image.png

8.在api/index.js內(nèi)把登錄接口和獲取用戶詳情和獲取動(dòng)態(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
    })
}
// 動(dòng)態(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ù)實(shí)際情況需要改成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ù)實(shí)際情況改,主要就是修改code值,如果,后端返回的code成功狀態(tài)值是200,那么這里就改成200。if (res.code === 50008 || res.code === 50012 || res.code === 50014)這里也根據(jù)后端返回的code按照實(shí)際情況來(lái)改,目前我沒(méi)有動(dòng)。

image.png

重點(diǎn)部分:開始了?。?!

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


image.png

12.這時(shí)候打開項(xiàng)目,點(diǎn)擊登錄,提示該用戶不存在,注意,本模版默認(rèn)傳給后端的是key值是username、password,而后端要求的key是loginame、password,把loginForm對(duì)象內(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,把a(bǔ)ctions中的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.這時(shí)候打開項(xiàng)目,點(diǎn)擊登錄,提示賬號(hào)密碼錯(cuò)誤,說(shuō)明接口已經(jīng)跑通。


image.png

14.我們輸入正確的賬號(hào)密碼 admin 123456 ,點(diǎn)擊登錄,登錄成功是這樣的


image.png

可以看到,因?yàn)檫€沒(méi)請(qǐng)求獲取動(dòng)態(tài)路由的接口,所以側(cè)邊欄是空的,頭像也是裂的,下面我們就來(lái)解決這些問(wèn)題。

15.頭像裂是因?yàn)?,我們還沒(méi)請(qǐng)求用戶信息,現(xiàn)在來(lái)操作
首先打開store/modules/user.js,把getInfo這個(gè)方法改造成這樣:(因?yàn)楹笈_(tái)我沒(méi)設(shè)計(jì)頭像,存?zhèn)€死值,各位老表自己根據(jù)自己后端實(shí)際返回的來(lái)存)


image.png

然后,頭像就正常了

16.下面做渲染側(cè)邊欄,請(qǐng)求動(dòng)態(tài)路由,請(qǐng)求接口之前,要先做一些配置:
(1)先在router這個(gè)目錄下新建兩個(gè)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)在最底部新寫一個(gè)方法


image.png

這時(shí)候點(diǎn)擊登錄,報(bào)錯(cuò),別著急。繼續(xù)往下走


image.png

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


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

這時(shí)候點(diǎn)擊登錄,會(huì)報(bào)這個(gè)錯(cuò):


image.png

意思就是找不到vue文件,根據(jù)實(shí)際情況,新建文件:
(8)在views下新建:system文件夾,文件夾內(nèi)新建三個(gè)文件夾,分別是 menu 、 roles 、user ,三個(gè)文件夾下分別新建index.vue
這時(shí)候在點(diǎn)擊登錄,不報(bào)錯(cuò),進(jìn)來(lái)了,但是側(cè)邊欄還是沒(méi)東西,還差一步:
(9)打開layout/components/Sidebar/index.vue,計(jì)算屬性中,把routes改成


image.png

這時(shí)候在刷新頁(yè)面,完美展示:


image.png

17.下面準(zhǔn)備開始開發(fā)菜單管理頁(yè)面。老規(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

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

在components/System下新建一個(gè)Toobar.vue文件,里面這樣寫:

<template>
  <div>
    <!--工具欄-->
    <div class="head_container">
      <span>
        <el-input
          class="filter-item"
          v-model="searchKey"
          clearable
          placeholder="請(qǐng)輸入內(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, }, },這段代碼是接收的父組件傳過(guò)來(lái)的添加按鈕權(quán)限,后面會(huì)講到

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

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

在menu/index.vue內(nèi)使用,出現(xiàn)說(shuō)明成功,但是太大了,在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;
里面暫時(shí)這樣寫:

<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="請(qǐng)輸入標(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="請(qǐng)排序"></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="請(qǐng)輸入組件name"></el-input>
          </el-form-item>
          <el-form-item label="組件路徑" style="margin-left: 15px" prop="component">
            <el-input placeholder="請(qǐng)輸入組件路徑" @input="change($event)" v-model="formData.component"></el-input>
          </el-form-item>
        </div>
        <!-- 按鈕名稱、權(quán)限標(biāo)識(shí) -->
        <div class="flex" style="display: flex" v-if="formData.type == 3">
          <el-form-item label="按鈕名稱" prop="title">
            <el-input placeholder="請(qǐng)輸入按鈕名稱" v-model="formData.title"></el-input>
          </el-form-item>
          <el-form-item label="權(quán)限標(biāo)識(shí)" style="margin-left: 15px" prop="permissions">
            <el-input placeholder="請(qǐng)輸入權(quán)限標(biāo)識(shí)" v-model="formData.permissions"></el-input>
          </el-form-item>
        </div>
        <!--上級(jí)類目-->
        <div class="flex" style="display: flex">
          <el-form-item label="上級(jí)類目" prop="pid">
            <el-cascader :options="allMenu" v-model="formData.pid" placeholder="請(qǐng)選擇" :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="請(qǐng)排序"></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),來(lái)自阿里媽媽
        eIconSymbol: false, //是否開啟彩色圖標(biāo)
        addIconList: [],
        removeIconList: [],
      },
      rules: {
        title: [{ required: true, message: "請(qǐng)輸入標(biāo)題", trigger: "blur" }],
        icon: [{ required: true, message: "請(qǐng)選擇圖標(biāo)", trigger: "blur" }],
        sort: [{ required: true, message: "請(qǐng)輸入排序編號(hào)", trigger: "blur" }],
        name: [{ required: true, message: "請(qǐng)輸入組件name", trigger: "blur" }],
        path: [{ required: true, message: "請(qǐng)輸入組件路徑", trigger: "blur" }],
        icon: [{ required: true, message: "請(qǐng)選擇圖標(biāo)", trigger: "change" }],
        pid: [{ required: true, message: "請(qǐng)選擇上級(jí)類目", trigger: "change" }],
        component: [
          { required: true, message: "請(qǐng)輸入組件路徑", trigger: "blur" },
        ],
        permissions: [
          { required: true, message: "請(qǐng)輸入權(quán)限標(biāo)識(shí)", trigger: "blur" },
        ],
      },
    };
  },
  created () {
    this.init();
  },
  watch: {
    "formData.type": {
      handler: function () {
        if (this.formData.type == "1") {
          this.formData.redirect = "noRedirect"; //建議 必須是 ‘noRedirect’,因?yàn)槿绻莚edirect的話面包屑那一塊是可以點(diǎn)擊跳轉(zhuǎn),這樣做沒(méi)有意義
          this.formData.alwaysShow = "1"; //設(shè)置成1 意思是總是顯示父級(jí),-----如果沒(méi)這個(gè)字段或者這個(gè)字段為0 意思就是當(dāng)只有一個(gè)子菜單的時(shí)候,不顯示父級(jí)
          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: "頂級(jí)目錄",
          });
        }
        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;
                });
              }
            });
          }
        }
      });
    },
    //點(diǎn)擊確定按鈕提交
    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)識(shí)" 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",
      };

    },
    //提交新增請(qǐng)求
    handleSubmit (formData) {
      addMenu(this.formData).then((res) => {
        console.log(res);
        this.dialogMenu.show = false;
        this.$message.success("新增成功!");
        if (this.formData.pid != 0) {
          // 實(shí)現(xiàn)無(wú)感刷新
          getMenuList({ pid: this.formData.pid }).then((res) => {
            this.$set(
              this.$refs.table.store.states.lazyTreeNodeMap,
              this.formData.pid,
              res.data
            );
          });
        } else {
          this.init();
        }
      });
    },
    //編輯請(qǐng)求
    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("點(diǎn)擊觸發(fā)")
      console.log(this.$refs)
      this.$confirm(
        "此操作將永久刪除該菜單,并刪除所屬子級(jí), 是否繼續(xù)?",
        "提示",
        {
          confirmButtonText: "確定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          delMenu(row._id).then((res) => {
            this.$message({
              type: "success",
              message: "刪除成功!",
            });
            // 無(wú)感刷新
            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.因?yàn)橛玫絜-icon-picker選擇圖標(biāo)的插件,所以要安裝下:


image.png

21.菜單就可以了。


image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請(qǐng)通過(guò)簡(jiǎn)信或評(píng)論聯(lián)系作者。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容