如何停止vue组件不调用mounted
How to stop the vue component to not call mounted
这是我的混音
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
为 null 它给出 TypeError
即 Cannot read property 'token' of null
。虽然我可以通过检查是否设置了 currentUser
来保护我的 getOrders
函数,但是我必须在许多其他函数中这样做。我想要发生的是,在 created
挂钩安装之后不应该被调用或任何其他任何人更了解的技术?
你可以使用路由功能beforeRouteEnter
,如果应用没有授权,你可以在进入需要授权的页面之前重定向到其他页面
而不是检查用户在 mixin 中的身份验证使用 global navigation guards。
您可以使用 beforeEach
或 beforeResolve
来检查 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;
这是我的混音
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
为 null 它给出 TypeError
即 Cannot read property 'token' of null
。虽然我可以通过检查是否设置了 currentUser
来保护我的 getOrders
函数,但是我必须在许多其他函数中这样做。我想要发生的是,在 created
挂钩安装之后不应该被调用或任何其他任何人更了解的技术?
你可以使用路由功能beforeRouteEnter
,如果应用没有授权,你可以在进入需要授权的页面之前重定向到其他页面
而不是检查用户在 mixin 中的身份验证使用 global navigation guards。
您可以使用 beforeEach
或 beforeResolve
来检查 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;