Learn to use the Vue router tab to switch

 

Original address: https://bhuh12.github.io/vue-router-tab/zh/guide/advanced/cache.html#%E9%A1%B5%E7%AD%BE%E7%BC%93%E5%AD%98

Cache control

Tab cache

RouterTab caches the pages of each tab by default

You can set the of the RouterTab component   keep-alive   This behavior can also be cancelled through routing   meta.keepAlive   To override the default configuration of the component

If the tab cache is cancelled, the component instance will be re created each time you enter the tab

Global configuration

<router-tab :keep-alive="false" />

Routing configuration

const route = {
  path: '/my-page/:1',
  component: MyPage,
  meta: {
    title: 'page',
    keepAlive: false
  }
}

Maximum number of caches

You can set the RouterTab component   max-alive   To control the maximum number of caches on the tab, which is   0   (default) there is no limit

When the number of tabs exceeds the set value, the initially opened tab cache will be cleaned up

<router-tab :max-alive="10" />

Reuse component

By default, the route of the same tab is opened again. If the route is   params   or   query   If the change occurs, RouterTab will clean up the last page cache and recreate the page instance

You can set the RouterTab component   reuse   This behavior can also be cancelled through routing   meta.reuse   To override the default configuration of the component

Tips

If set   reuse   by   true, you may need to listen  $ route   or   activated   Hook to update page data

Global configuration

<router-tab :reuse="true" />

Routing configuration

const route = {
  path: '/my-page/:1',
  component: MyPage,
  meta: {
    title: 'page,
    reuse: true // In different ways params or query After reopening the tab, the previous page will be reused and will not be recreated
  }
}

Dynamic tab

RouterTab listens for components   this.routeTab   To dynamically update tab information. You can set   this.routeTab   To change the title, icon and prompt of the tab.

# Calculate attributes through computed (recommended)

Example:

export default {
  name: 'GoodsDetail',
  data() {
    return {
      goods: {
        goodsName: 'Trade name',
        goodsDesc: 'Product introduction'
      }
    }
  },
  computed: {
    // Update tab by calculation attribute
    routeTab() {
      // 1. Update tab title only
      return `commodity-${this.goods.goodsName}`

      // 2. Update multiple tab information
      return {
        title: `commodity-${this.goods.goodsName}`,
        icon: 'el-icon-goods',
        tips: this.goods.goodsDesc
      }

      // 3. Internationalization tab title
      return {
        // Define internationalization with parameter list in array, format:['i18nKey', ...params]
        title: ['routerTab.goods', this.goods.goodsName]
      }
    }
  }
}

Respond to data via data

Example:

export default {
  name: 'GoodsDetail',
  data() {
    return {
      goods: {
        goodsName: 'Trade name',
        goodsDesc: 'Product introduction'
      },
      routeTab: null // routeTab Store in data To support response
    }
  },
  mounted() {
    setTimeout(() => {
      // Update tab after asynchrony
      this.routeTab = {
        title: `commodity-${this.goods.goodsName}`,
        icon: 'el-icon-goods',
        tips: this.goods.goodsDesc
      }
    }, 300)
  }
}

Configure via routing meta

Example:

const route = {
  path: '/my-page/:id',
  component: MyPage,
  meta: {
    title: route => `page ${route.params.id}`
  }
}

Initial display tab

By configuring the of the RouterTab component   tabs   Property, you can set the default tab displayed when entering the page.

be careful

In the Nuxt project, if the tab configuration comes from the page   meta, the configuration of the inactive tab cannot be obtained automatically. Therefore, this scenario cannot be passed only through   fullpath   Method configuration initial tab.

Example:

<template>
  <router-tab :tabs="tabs" />
</template>

<script>
export default {
  name: 'InitialTabs',
  data() {
    return {
      tabs: [
        // Just set fullpath,The program will automatically start from router Get the title of the tab in configuration/Icons and other information
        // (Nuxt project page meta Tab routing mode configuration (not supported)
        '/initial-tabs/page-leave',

        // Nuxt The project requires the complete configuration of the tab display
        { to: '/initial-tabs/tab-dynamic', title: 'Asynchronous tab', closable: false },

        // For tabs with dynamic tab titles, you need to set the initial tab title to avoid inconsistent titles after entering the tab
        { to: '/initial-tabs/page/1', title: 'Page 1' },

        // <router-link> location Mode configuration
        {
          to: {
            path: '/initial-tabs/page/2',
            query: { t: 2 }
          },

          title: 'Page 2'
        },

        // default key Under configuration, this tab is the same as '/initial-tabs/page/2' Tab key If it is consistent, only the first tab will be retained
        { to: '/initial-tabs/page/2?t=1', title: 'Page 2-1' },

        // Iframe Tab
        `/initial-tabs/iframe/${encodeURIComponent(
          'https://cn.vuejs.org'
        )}/Vue.js/rt-icon-web`
      ]
    }
  }
}
</script>

Restore after refresh tab

Setting for RouterTab component   restore   Property, you can set the Restore tab after browser refresh.

RouterTab stores tab cache information through sessionStorage

Default mode

<router-tab restore />

Custom cache

RouterTab supports customizing locally stored keys and obtaining the corresponding cache according to the given key

In practical application, we want to store browser tab information according to the current user.

<router-tab :restore="userInfo.userId" />

Listen for the restore parameter

Usually, our data will be obtained asynchronously from the server. If we want to restore the tab according to the user after the user data is obtained, it can be configured   restore-watch   To listen to the restore parameter and automatically restore the corresponding user's tab after changing

<router-tab :restore="userInfo.userId" restore-watch />

Page departure confirmation

Triggered when the tab closes, refreshes, replaces, leaves the current route, or the browser window closes and refreshes   beforePageLeave, via   Promise   To allow or prevent the departure of tab pages.

be careful

beforePageLeave   On the outermost layer of the component, not on the   methods   in

Example:

export default {
  /**
   * Confirm before leaving the page
   * @param {Object} tab Tab information
   * @param {String} type Departure type:
   *   close: Tab close
   *   refresh: Tab refresh
   *   replace: Tab replaced
   *   leave: Route away
   *   unload: Browser refresh or close
   * @returns {String|Promise}
   */
  beforePageLeave(tab, type) {
    // If the value is not changed, you can leave the tab directly
    if (this.editValue === this.value) return

    // When the browser window is refreshed or closed, the supported browsers will display a confirmation message
    if (type === 'unload') {
      return `You are“ ${tab.title}"The tab has not been changed yet. Do you want to leave?`
    }

    // Leave type
    const action = {
      close: 'close',
      refresh: 'Refresh',
      replace: 'replace',
      leave: 'leave'
    }[type]

    const msg = `Are you sure you want to ${action}Tab“ ${tab.title}"Are you?`

    // return promise,resolve Leave, reject Stop leaving
    return new Promise((resolve, reject) => {
      // If the value changes, confirm the prompt
      if (confirm(msg)) {
        resolve()
      } else {
        reject(`You refused ${action}Tab`)
      }
    })

    // Used here Element of confirm assembly
    // Need to closeOnHashChange Configure as false,To avoid route switching causing the confirmation box to close
    // return this.$confirm(msg, 'Tips', { closeOnHashChange: false })
  }
}

 

Added by kee1108 on Fri, 03 Dec 2021 17:39:51 +0200