Vue項目常見場景需求的解決方案


一、頁面權限控制

  頁面權限控制是什么意思呢?就是一個網站有不同的角色,比如管理員和普通用戶,要求不同的角色能訪問的頁面是不一樣的。如果一個頁面,有角色越權訪問,這時就得做出限制了。

  一種方法是通過動態添加路由和菜單來做控制,不能訪問的頁面不添加到路由表里,這是其中一種辦法。

  另一種辦法就是所有的頁面都在路由表里,只是在訪問的時候要判斷一下角色權限。如果有權限就允許訪問,沒有權限就拒絕,跳轉到 404 頁面。

1、思路

  在每一個路由的 meta 屬性里,將能訪問該路由的角色添加到 roles 里。用戶每次登陸后,將用戶的角色返回。然后在訪問頁面時,把路由的 meta 屬性和用戶的角色進行對比,如果用戶的角色在路由的 roles 里,那就是能訪問,如果不在就拒絕訪問。

2、代碼示例

// 路由信息
 { path: '/company', name: 'company', component: Company, meta: { roles: ['ROLE_sys'],  // 代表角色
      permission: 'company'  // 代表權限
 } },
// 路由鑒權
  app.router.beforeEach((to, from, next) => { let invalid = !to.matched || to.matched.length === 0
    if (invalid) { redirect('/') return } let _token = store.getters.token if (_token) { // 判斷是否有路由的查看權限
      const userInfo = resolveToken(_token) let _per = userInfo.permissions let _meta = to.meta // 1、角色判斷;2、權限判斷
      if ( (_meta.roles && !_meta.roles.includes(userInfo.roleName)) && (_per && !_per.includes(_meta.permission)) ) { message({ message: '您無權訪問此頁面', type: 'error' }) redirect('/') } } })

  一個是角色判斷、一個是權限判斷,均可以放在路由meta信息里。

二、登錄校驗

  項目里的頁面有的是公開的,完全不需登錄即可查看;有的是非公開的,需要登錄才能查看。一般只要登陸過一次后,接下來該網站的其他頁面都是可以直接訪問的,不用再次登陸。我們可以通過 token 或 cookie 來實現,下面用代碼來展示一下如何用 token 控制登陸驗證。

router.beforeEach((to, from, next) => { // 如果有token 說明該用戶已登陸
    if (localStorage.getItem('token')) { // 在已登陸的情況下訪問登陸頁會重定向到首頁
        if (to.path === '/login') { next({path: '/'}) } else { next({path: to.path || '/'}) } } else { // 沒有登陸則訪問任何頁面都重定向到登陸頁
        if (to.path === '/login') { next() } else { next(`/login?redirect=${to.path}`) } } })

  這種需求很簡單,但是我們實際場景其實還有更復雜的需求,可以看我之前寫的博客,需求就復雜很多:vue-router登錄校驗后跳轉到之前指定頁面如何實現

三、動態菜單

  寫后台管理系統,估計有不少人遇過這樣的需求:根據后台數據動態添加路由和菜單。為什么這么做呢?因為不同的用戶有不同的權限,能訪問的頁面是不一樣的。

 1、動態添加路由

  利用 vue-router 的 addRoutes 方法可以動態添加路由。

  先看一下官方介紹:router.addRoutes(routes: Array<RouteConfig>),動態添加更多的路由規則。參數必須是一個符合 routes 選項要求的數組。

// 比如常規的這樣
const router = new Router({ routes: [ { path: '/login', name: 'login', component: () => import('../components/Login.vue') }, {path: '/', redirect: '/home'}, ] }) // 上面的代碼和下面的代碼效果是一樣的
const router = new Router({ routes: [ {path: '/', redirect: '/home'}, ] }) router.addRoutes([ { path: '/login', name: 'login', component: () => import('../components/Login.vue') } ])

  在動態添加路由的過程中,如果有 404 頁面,一定要放在最后添加,否則在登陸的時候添加完頁面會重定向到 404 頁面。

// 類似於這樣,這種規則一定要最后添加。
{path: '*', redirect: '/404'}

2、動態生成菜單

  假設后台返回來的數據長這樣:

// 左側菜單欄數據
menuItems: [ { name: 'home', // 要跳轉的路由名稱 不是路徑
        size: 18, // icon大小
        type: 'md-home', // icon類型
        text: '主頁' // 文本內容
 }, { text: '二級菜單', type: 'ios-paper', children: [ { type: 'ios-grid', name: 't1', text: '表格' }, { text: '三級菜單', type: 'ios-paper', children: [ { type: 'ios-notifications-outline', name: 'msg', text: '查看消息' }, ] } ] } ]

  來看看怎么將它轉化為菜單欄,我在這里使用了 iview 的組件,不用重復造輪子。

<!-- 菜單欄 -->
<Menu ref="asideMenu" theme="dark" width="100%" @on-select="gotoPage" accordion :open-names="openMenus" :active-name="currentPage" @on-open-change="menuChange">
    <!-- 動態菜單 -->
    <div v-for="(item, index) in menuItems" :key="index">
        <Submenu v-if="item.children" :name="index">
            <template slot="title">
                <Icon :size="item.size" :type="item.type"/>
                <span v-show="isShowAsideTitle">{{item.text}}</span>
            </template>
            <div v-for="(subItem, i) in item.children" :key="index + i">
                <Submenu v-if="subItem.children" :name="index + '-' + i">
                    <template slot="title">
                        <Icon :size="subItem.size" :type="subItem.type"/>
                        <span v-show="isShowAsideTitle">{{subItem.text}}</span>
                    </template>
                    <MenuItem class="menu-level-3" v-for="(threeItem, k) in subItem.children" :name="threeItem.name" :key="index + i + k">
                        <Icon :size="threeItem.size" :type="threeItem.type"/>
                        <span v-show="isShowAsideTitle">{{threeItem.text}}</span>
                    </MenuItem>
                </Submenu>
                <MenuItem v-else v-show="isShowAsideTitle" :name="subItem.name">
                    <Icon :size="subItem.size" :type="subItem.type"/>
                    <span v-show="isShowAsideTitle">{{subItem.text}}</span>
                </MenuItem>
            </div>
        </Submenu>
        <MenuItem v-else :name="item.name">
            <Icon :size="item.size" :type="item.type" />
            <span v-show="isShowAsideTitle">{{item.text}}</span>
        </MenuItem>
    </div>
</Menu>

  代碼不用看得太仔細,理解原理即可,其實就是通過三次 v-for 不停的對子數組進行循環,生成三級菜單。

  不過這個動態菜單有缺陷,就是只支持三級菜單。一個更好的做法是把生成菜單的過程封裝成組件,然后遞歸調用,這樣就能支持無限級的菜單。在生成菜單時,需要判斷一下是否還有子菜單,如果有就遞歸調用組件

  動態路由因為上面已經說過了用 addRoutes 來實現,現在看看具體怎么做。

const asyncRoutes = { 'home': { path: 'home', name: 'home', component: () => import('../views/Home.vue') }, 't1': { path: 't1', name: 't1', component: () => import('../views/T1.vue') }, 'password': { path: 'password', name: 'password', component: () => import('../views/Password.vue') }, 'msg': { path: 'msg', name: 'msg', component: () => import('../views/Msg.vue') }, 'userinfo': { path: 'userinfo', name: 'userinfo', component: () => import('../views/UserInfo.vue') } } // 傳入后台數據 生成路由表
menusToRoutes(menusData) // 將菜單信息轉成對應的路由信息 動態添加
function menusToRoutes(data) { const result = [] const children = [] result.push({ path: '/', component: () => import('../components/Index.vue'), children, }) data.forEach(item => { generateRoutes(children, item) }) children.push({ path: 'error', name: 'error', component: () => import('../components/Error.vue') }) // 最后添加404頁面 否則會在登陸成功后跳到404頁面
 result.push( {path: '*', redirect: '/error'}, ) return result } function generateRoutes(children, item) { if (item.name) { children.push(asyncRoutes[item.name]) } else if (item.children) { item.children.forEach(e => { generateRoutes(children, e) }) } }

  首先,要把項目所有的頁面路由都列出來,再用后台返回來的數據動態匹配,能匹配上的就把路由加上,不能匹配上的就不加。

  最后,把這個新生成的路由數據用 addRoutes 添加到路由表里。

四、前進刷新后退不刷新

1、需求一:

  在一個列表頁中,第一次進入的時候,請求獲取數據。

  點擊某個列表項,跳到詳情頁,再從詳情頁后退回到列表頁時,不刷新。

  也就是說從其他頁面進到列表頁,需要刷新獲取數據,從詳情頁返回到列表頁時不要刷新。

解決方案:利用緩存組件

// 在 App.vue設置:
<keep-alive include="list">
    <router-view/>
</keep-alive>

  假設列表頁為 list.vue,詳情頁為 detail.vue,這兩個都是子組件。我們在 keep-alive 添加列表頁的名字,緩存列表頁。然后在列表頁的 created 函數里添加 ajax 請求,這樣只有第一次進入到列表頁的時候才會請求數據,當從列表頁跳到詳情頁,再從詳情頁回來的時候,列表頁就不會刷新。這樣就可以解決問題了。

2、需求二:

  在需求一的基礎上,再加一個要求:可以在詳情頁中刪除對應的列表項,這時返回到列表頁時需要刷新重新獲取數據。

解決方案一:

  我們可以在路由配置文件上對 detail.vue 增加一個 meta 屬性。

{   path: '/detail',   name: 'detail',   component: () => import('../view/detail.vue'),   meta: {isRefresh: true} },

  這個 meta 屬性,可以在詳情頁中通過 this.$route.meta.isRefresh 來讀取和設置。

  設置完這個屬性,還需要設置 watch 一下 $route 屬性。

watch: { $route(to, from) { const fname = from.name const tname = to.name if (from.meta.isRefresh || (fname != 'detail' && tname == 'list')) { from.meta.isRefresh = false
       // 在這里重新請求數據
 } } },

  觸發請求數據有兩個條件:

  1. 從其他頁面(除了詳情頁)進來列表時,需要請求數據。
  2. 從詳情頁返回到列表頁時,如果詳情頁 meta 屬性中的 isRefresh 為 true,也需要重新請求數據。

  當我們在詳情頁中刪除了對應的列表項時,就可以將詳情頁 meta 屬性中的 isRefresh 設為 true。這時再返回到列表頁,頁面會重新刷新。

解決方案二:

  對於需求二其實還有一個更簡潔的方案,那就是使用 router-view 的 key 屬性。

<keep-alive>
    <router-view :key="$route.fullPath"/>
</keep-alive>

  首先 keep-alive 讓所有頁面都緩存,當你不想緩存某個路由頁面,要重新加載它時,可以在跳轉時傳一個隨機字符串,這樣它就能重新加載了。

  例如從列表頁進入了詳情頁,然后在詳情頁中刪除了列表頁中的某個選項,此時從詳情頁退回列表頁時就要刷新,我們可以這樣跳轉:

this.$router.push({ path: '/list', query: { 'random': Math.random() }, })

  這樣的方案相對來說還是更簡潔的。

  還有更復雜的交互業務,也是我們項目上的,可以看之前寫的這篇博客:vue項目實現列表頁-詳情頁返回不刷新,再點其他菜單項返回刷新的需求

五、多個請求下 loading 的展示與關閉

  一般情況下,在 vue 中結合 axios 的攔截器控制 loading 展示和關閉,是這樣的:

  在 App.vue 配置一個全局 loading。

    <div class="app">
        <keep-alive :include="keepAliveData">
            <router-view/>
        </keep-alive>
        <div class="loading" v-show="isShowLoading">
            <Spin size="large"></Spin>
        </div>
    </div>

  同時設置 axios 攔截器。

// 添加請求攔截器
 this.$axios.interceptors.request.use(config => { this.isShowLoading = true
     return config }, error => { this.isShowLoading = false
     return Promise.reject(error) }) // 添加響應攔截器
 this.$axios.interceptors.response.use(response => { this.isShowLoading = false
     return response }, error => { this.isShowLoading = false
     return Promise.reject(error) })

  這個攔截器的功能是在請求前打開 loading,請求結束或出錯時關閉 loading。如果每次只有一個請求,這樣運行是沒問題的。但同時有多個請求並發,就會有問題了。

  假如現在同時發起兩個請求,在請求前,攔截器 this.isShowLoading = true 將 loading 打開。現在有一個請求結束了。this.isShowLoading = false 攔截器關閉 loading,但是另一個請求由於某些原因並沒有結束。造成的后果就是頁面請求還沒完成,loading 卻關閉了,用戶會以為頁面加載完成了,結果頁面不能正常運行,導致用戶體驗不好。

解決方案:

  增加一個 loadingCount 變量,用來計算請求的次數。再增加兩個方法,來對 loadingCount  進行增減操作。

    loadingCount: 0 methods: { addLoading() { this.isShowLoading = true
            this.loadingCount++ }, isCloseLoading() { this.loadingCount--
            if (this.loadingCount == 0) { this.isShowLoading = false } } }

  現在攔截器變成這樣:

        // 添加請求攔截器
        this.$axios.interceptors.request.use(config => { this.addLoading() return config }, error => { this.isShowLoading = false
            this.loadingCount = 0
            this.$Message.error('網絡異常,請稍后再試') return Promise.reject(error) }) // 添加響應攔截器
        this.$axios.interceptors.response.use(response => { this.isCloseLoading() return response }, error => { this.isShowLoading = false
            this.loadingCount = 0
            this.$Message.error('網絡異常,請稍后再試') return Promise.reject(error) })

  這個攔截器的功能是:

  每當發起一個請求,打開 loading,同時 loadingCount 加1。

  每當一個請求結束, loadingCount 減1,並判斷  loadingCount 是否為 0,如果為 0,則關閉 loading。

  這樣即可解決,多個請求下有某個請求提前結束,導致 loading 關閉的問題。

六、表格打印

  打印需要用到的組件為 print-js

 1、普通表格打印

  一般的表格打印直接仿照組件提供的例子就可以了。

printJS({ printable: id, // DOM id
    type: 'html', scanStyles: false, })

2、element-ui 表格打印(其他組件庫的表格同理)

   element-ui 的表格,表面上看起來是一個表格,實際上是由兩個表格組成的。表頭為一個表格,表體又是個表格,這就導致了一個問題:打印的時候表體和表頭錯位。另外,在表格出現滾動條的時候,也會造成錯位。

解決方案:

  我的思路是將兩個表格合成一個表格,print-js 組件打印的時候,實際上是把 id 對應的 DOM 里的內容提取出來打印。所以,在傳入 id 之前,可以先把表頭所在的表格內容提取出來,插入到第二個表格里,從而將兩個表格合並,這時候打印就不會有錯位的問題了。

function printHTML(id) { const html = document.querySelector('#' + id).innerHTML // 新建一個 DOM
    const div = document.createElement('div') const printDOMID = 'printDOMElement' div.id = printDOMID div.innerHTML = html // 提取第一個表格的內容 即表頭
    const ths = div.querySelectorAll('.el-table__header-wrapper th') const ThsTextArry = [] for (let i = 0, len = ths.length; i < len; i++) { if (ths[i].innerText !== '') ThsTextArry.push(ths[i].innerText) } // 刪除多余的表頭
    div.querySelector('.hidden-columns').remove() // 第一個表格的內容提取出來后已經沒用了 刪掉
    div.querySelector('.el-table__header-wrapper').remove() // 將第一個表格的內容插入到第二個表格
    let newHTML = '<tr>'
    for (let i = 0, len = ThsTextArry.length; i < len; i++) { newHTML += '<td style="text-align: center; font-weight: bold">' + ThsTextArry[i] + '</td>' } newHTML += '</tr>' div.querySelector('.el-table__body-wrapper table').insertAdjacentHTML('afterbegin', newHTML) // 將新的 DIV 添加到頁面 打印后再刪掉
    document.querySelector('body').appendChild(div) printJS({ printable: printDOMID, type: 'html', scanStyles: false, style: 'table { border-collapse: collapse }' // 表格樣式
 }) div.remove() }

七、下載二進制文件

  平時在前端下載文件有兩種方式,一種是后台提供一個 URL,然后前端使用一些方式下載,另一種就是后台直接返回文件的二進制內容,然后前端轉化一下再下載。由於第一種方式比較簡單,在此不做探討。主要講解一下第二種方式怎么實現。第二種方式需要用到 Blob 對象, mdn 文檔上是這樣介紹的:

Blob 對象表示一個不可變、原始數據的類文件對象。Blob 表示的不一定是JavaScript原生格式的數據

axios({ method: 'post', url: '/export', }) .then(res => { // 假設 data 是返回來的二進制數據
  const data = res.data const url = window.URL.createObjectURL(new Blob([data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"})) const link = document.createElement('a') link.style.display = 'none' link.href = url link.setAttribute('download', 'excel.xlsx') document.body.appendChild(link) link.click() document.body.removeChild(link) })

  打開下載的文件,看看結果是否正確。一堆亂碼,一定有哪里不對。

  最后發現是參數 responseType 的問題,responseType 它表示服務器響應的數據類型。由於后台返回來的是二進制數據,所以我們要把它設為 arraybuffer, 接下來再看看結果是否正確。

axios({ method: 'post', url: '/export', responseType: 'arraybuffer', }) .then(res => { // 假設 data 是返回來的二進制數據
  const data = res.data const url = window.URL.createObjectURL(new Blob([data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"})) const link = document.createElement('a') link.style.display = 'none' link.href = url link.setAttribute('download', 'excel.xlsx') document.body.appendChild(link) link.click() document.body.removeChild(link) })

  這次沒有問題,文件能正常打開,內容也是正常的,不再是亂碼。


免責聲明!

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



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