繁体   English   中英

在VUE.JS中重定向url时,有什么办法可以显示标题吗?

[英]Is there any way to display title when redirect a url in VUE JS?

目前,我有一个导航抽屉组件。 所以想法是这样的,当用户导航到主页或个人资料页面等任何导航时,标题将根据路线相应地改变。 例如,如果用户导航到主页(eg "/") ,标题将更改为“Home”,如果用户导航到个人资料页面(eg /profile) ,标题将更改为“Profile”。 但是,如果我直接访问任何 URL, eg /profile, /profile/list ,标题不会更改为“Profile”,而是标题将使用默认值“TEST”。 我应该在我的路线上实施一个watch方法来解决这个问题吗?

index.js

export const state = () => ({
  title: 'TEST',
})

export const getters = {
  getTitle: (state) => state.title
}

export const mutations = {
  setTitle(state, value) {
    state.title = value
  }
}

export const actions = {
  setTitle({ commit }, value) {
    commit('setTitle', value)
  }
}

NavigationDrawer.vue

<script>
export default {
  data: () => ({
    drawer: true,
    items: [
      {
        icon: 'mdi-home',
        title: 'Home',
        to: '/'
      },
      {
        icon: 'mdi-account',
        title: 'Profile',
        style: 'profile',
        links: [
          { title: 'Dashbord', to: '/profile/' },
          { title: 'Staff List', to: '/profile/list' },
          { title: 'Search', to: '/profile/search' },
        ]
      },
      {
        icon: 'mdi-umbrella-beach',
        title: 'E-Leave',
        style: 'leave',
        to: '/leave',
      },
      {
        icon: 'mdi-calendar-clock',
        title: 'Time Attendance',
        style: 'attendance',
        to: '/attendance'
      },
      {
        icon: 'mdi-car-lifted-pickup',
        title: 'Reservation',
        style: 'reservation',
        to: '/reservation'
      },
      {
        icon: 'mdi-weight-lifter',
        title: 'Staff Training',
        style: 'training',
        links: [
          { title: 'Training Records', to: '/training/records' },
          { title: 'Training Programs', to: '/training/programs' },
        ]
      },
      {
        icon: 'mdi-medical-bag',
        title: 'Medical',
        style: 'medical',
        links: [
          { title: 'My Balances', to: '/medical/balance/self' },
        ]
      },
    ],
  }),

  methods: {
  getCurrentPageNameByPath(){
      var array = [
          { name:"Profile", value:"/profile/"},
      ];
      const search = what => array.find(element => element.name === what);
      const found = search("Profile");
      if (found) {
          console.log(found.value, found.other);
      } else {
          console.log('No result found');
      }
    },
    updatePageTitle(title) {
      this.$store.dispatch('setTitle', title)
    },
    toggleDrawer() {
      this.drawer = !this.drawer;
    },
    isAdminChipVisible(link) {
        return (link.hasOwnProperty('is_hr') && link.is_hr) || (link.hasOwnProperty('is_hod') && link.is_hod);
    },
    isVisibleForRegularUser(link, item) {
      return item.public || ( this.$auth.user && (!link.hasOwnProperty('is_hod') || link.is_hod == false)  && (!link.hasOwnProperty('is_hr') || link.is_hr == false) );
    },
    isVisibleForHod(link, item) {
      return item.public || ( this.$auth.user && (link.hasOwnProperty('is_hod') && link.is_hod) && this.$auth.user.is_hod );
    },
    isVisibleForHrAdmin(link, item) {
      return item.public || ( this.$auth.user && (link.hasOwnProperty('is_hr') && link.is_hr) && this.$auth.user.is_hr_admin );
    }
  },

  mounted() {
    const currentPath = this.$router.currentRoute.path
   const currentPageName = this.getCurrentPageNameByPath(currentPath)

   this.$store.dispatch("setTitle",currentPageName)
    this.$nextTick(() => {
      if (this.$vuetify.breakpoint.mdAndDown) this.drawer = false
    })

  },
}
</script>

<template class="nav-color-gradient">
  <v-navigation-drawer
    class="nav-color-gradient"
    v-model="drawer"
    :width="300"
    app
    dark
    fixed
    floating
  >
    <template v-slot:prepend>
      <div class="navigation-drawer__spacer">
        <div class="text-center my-5">
        <img src="/snet_white.png" height="50" />
        </div>
      </div>
    </template>
    <template v-slot:append>
      <div class="navigation-drawer__spacer"></div>
    </template>
    <template v-slot:default>
      <v-list class="py-0">
        <template
          v-for="(item, index) in items"
        >
          <v-list-group
            v-if="item.links"
            :append-icon="null"
            :group="item.to"
            :ripple="false"
            v-bind:key="index"
            router
          >
            <template v-slot:activator>
              <v-list-item-content>
                <v-list-item-title
                  class="text-right"
                  v-text="item.title.toUpperCase()"
                >
                </v-list-item-title>
              </v-list-item-content>
              <v-list-item-action>
                <v-icon>{{ item.icon }}</v-icon>
              </v-list-item-action>
            </template>

            <template v-for="(link, l) in item.links">

              <!-- for hod -->
              <v-list-item
                v-if="isVisibleForHod(link, item)"
                :key="l"
                :class="item.style"
                :ripple="false"
                :to="link.to"
                exact
                router
                @click="updatePageTitle([item.title, link.title])"
              >
                <v-list-item-title class="text-right">
                  <v-chip v-if="isAdminChipVisible(link)" color="white float-left" x-small>ADMIN</v-chip>
                  {{link.title.toUpperCase()}}
                </v-list-item-title>
              </v-list-item>


              <!-- for hr admin -->
              <v-list-item
                v-else-if="isVisibleForHrAdmin(link, item)"
                :key="l"
                :class="item.style"
                :ripple="false"
                :to="link.to"
                exact
                router
                @click="updatePageTitle([item.title, link.title])"
              >
                <v-list-item-title class="text-right">
                  <v-chip v-if="isAdminChipVisible(link)" color="white float-left" x-small>ADMIN</v-chip>
                  {{link.title.toUpperCase()}}
                </v-list-item-title>
              </v-list-item>

              <!-- for regular staff -->
              <v-list-item v-else-if="isVisibleForRegularUser(link, item)"
                :key="l"
                :class="item.style"
                :ripple="false"
                :to="link.to"
                exact
                router
                @click="updatePageTitle([item.title, link.title])"
              >
                <v-list-item-title class="text-right">
                  {{link.title.toUpperCase()}}
                </v-list-item-title>
              </v-list-item>

            </template>
          </v-list-group>

          <v-list-item
            exact-active-class="primary--text"
            :ripple="false"
            :to="item.to"
            v-bind:key="index"
            exact
            router
            v-else
            @click="updatePageTitle(item.title)"
          >
            <v-list-item-content>
              <v-list-item-title
                class="text-right"
                v-text="item.title.toUpperCase()"
              >
              </v-list-item-title>
            </v-list-item-content>
            <v-list-item-action>
              <v-icon>{{ item.icon }}</v-icon>
            </v-list-item-action>
          </v-list-item>
        </template>
      </v-list>
    </template>
  </v-navigation-drawer>
</template>

我为你推荐两种方法来做到这一点:

1 - 您可以在每个页面的挂载上分派“setTitle”操作。 例如,在 Profile.vue 页面上,您应该添加以下代码:

mounted(){
    // Current page Name is the page Name, in this case it's Profile
    this.$store.dispatch("setTitle",currentPageName)
}

2 - 您可以在“NavigationDrawer.vue”文件的“created”或“mounted”方法中从当前路由 url 中提取页面名称,然后通过传递页面名称来调度新的 Action“setTitle”:

mounted(){
   // your code 
   ......
   // 1 - Get current path from router
   const currentPath = this.$router.currentRoute.path
   // 2 - Search for page Name in items array , you can create a method
   // (getCurrentPageNameByPath) for doing this task
   const currentPageName = getCurrentPageNameByPath(currentPath)
   // 3 - dispatch cureent page name
   this.$store.dispatch("setTitle",currentPageName)
}

methods : {
   getCurrentPageNameByPath(path){
      let path = '/profile/'
      let currentPageName = ''

      for(let item of items){
         if(item.links) {
             for(let nestdItem of item.links ){
                 if(nestdItem.to == path) {
                    currentPageName = item.title;
                    break;
                 }
            }  
         }else {
              if(item.to == path) {
              currentPageName = item.title;
              break;
         }
       }
     }

     console.log(currentPageName)
     return currentPageName
   }

}

您可以使用 beforeRouteEnter 挂钩,

beforeRouteEnter (to, from, next) {
// document.title = to.title; // Optional set page title from here as well 
store.dispatch("setTitle",to.title);
next();

}

您必须导入商店,因为您无法在路由器挂钩中访问 $store

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM