简体   繁体   English

如何停止Vue组件不挂载

[英]How to stop the vue component to not call mounted

This is my mixin 这是我的混蛋

export default {
  created () {
    if (!this.$store.getters.isAuthenticated) {
      this.$router.replace('/start')
    }
  }
}

This is my component:- 这是我的组件:

import Auth from '../auth'

export default {
  mixins: [Auth],
  computed: {
    orders () {
      return this.$store.getters.orders
    }
  },
  mounted () {
    this.$store.dispatch('getOrders')
  }
}

Store:- 商店:-

async getOrders ({ commit, state }) {
  const res = await axios.get(`${API_URL}/orders`, {
    headers: {
      'authorization': state.currentUser.token
    }
  })
  commit('setOrders', res.data)
}

The problem I am facing is, although it does redirect to '/start' when I go to '/orders' , but it also start fetching the orders from mounted hook, and since currentUser is null it is giving a TypeError that Cannot read property 'token' of null . 我面临的问题是,尽管当我转到'/orders' '/start'时确实重定向到'/start' ,但它也开始从已mounted钩子中获取订单,并且由于currentUser为null,因此它给出了TypeErrorCannot read property 'token' of null Although I can guard my getOrders function with a check if currentUser is set or not, but then I have to do it in many other functions. 尽管我可以通过检查是否设置了currentUser来保护getOrders函数,但是然后我必须在许多其他函数中进行设置。 What I would like to happen is that after created hook mounted should not get called or any other technique anyone know better? 我想发生的事情是,在created挂接的钩子之后,不应调用任何其他人更了解的技术?

您可以在beforeRouteEnter使用路由功能,如果应用尚未通过身份验证,则可以在进入需要身份验证的页面之前重定向到其他页面

Instead of checking it the user is authenticated in a mixin use global navigation guards . 不用检查它,而是使用全局导航防护在mixin中对用户进行身份验证。

You can either use beforeEach or beforeResolve to check if the currentUser is not null. 您可以使用beforeEachbeforeResolve以检查currentUser不为空。

  import store from './store'; // import your Vuex store

  const router = new VueRouter({
    routes: [{
      name: 'orders',
      path: '/orders',
      meta: {
        requiresAuth: true // use this in the routes that need your currentUser
      }
    }],
  });

  router.beforeResolve((to, from, next) => {
    if (to.matched.some(record => record.meta.requiresAuth)) {
      if (!this.$store.getters.isAuthenticated || !store.state.currentUser) {
        next({
          name: 'forbidden' // the route the guest will be redirected to
        });
      } else {
        next();
      }
    } else {
      next();
    }
  });

  export default router;

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

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