【问题标题】:How to stop the vue component to not call mounted如何停止vue组件不调用mounted
【发布时间】:2018-03-06 14:22:51
【问题描述】:

这是我的混音

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

这是我的组件:-

import Auth from '../auth'

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

商店:-

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

我面临的问题是,虽然当我转到'/orders' 时它确实重定向到'/start',但它也开始从mounted 钩子中获取订单,并且由于currentUser 为空,它给出了一个TypeError 那个Cannot read property 'token' of null。虽然我可以通过检查currentUser 是否设置来保护我的getOrders 函数,但是我必须在许多其他函数中执行此操作。我想要发生的是,在 created 挂载后不应该调用挂钩或任何其他人更了解的技术?

【问题讨论】:

  • 您应该在getOrders 中检查currentUser

标签: vue.js vuejs2 vue-router vuex


【解决方案1】:

用户在 mixin 使用 global navigation guards 中进行身份验证,而不是检查它。

您可以使用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;

【讨论】:

    【解决方案2】:

    你可以使用路由功能beforeRouteEnter,如果app没有认证,你可以在进入需要认证的页面前重定向到其他页面

    【讨论】:

      猜你喜欢
      • 2018-11-08
      • 2018-07-31
      • 2021-02-20
      • 2018-02-27
      • 2018-07-18
      • 2019-03-29
      • 2017-12-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多