Dry*_*ams 7 vue-router vuex vuejs2
用户通过登录表单成功登录我的应用程序后.我想检查一下他们是否有个人资料.如果他们这样做,我想将他们发送到新闻页面.如果他们没有一套,我希望它将它们重定向到"设置"页面.我如何使用Vuex做到这一点?
我想有几个选择:
Login.vue
handleFormSubmit () {
this.$store.dispatch('loginFormSubmit', formData)
.then(() => {
// This feels a bit gross
this.$store.dispatch('getUserProfile')
.then(() => this.$router.push('/news'))
.catch(() => this.$router.push('/settings'))
})
.catch(() => {
this.loginError = true
})
}
Run Code Online (Sandbox Code Playgroud)
用户actions.js
export const getUserProfile = ({commit}) => {
commit(types.USER_PROFILE_REQUEST)
const options = {
url: `${API_URL}/profile`,
method: 'GET'
}
return request(options)
.then((profileSettings) => {
// Would I change the router to News here??
commit(types.USER_PROFILE_SUCCESS, profileSettings)
return Promise.resolve(profileSettings)
})
.catch((error) => {
// Would I change the router to Settings here??
commit(types.UI_MENU_HIDE)
return Promise.reject(error)
})
}
export const loginFormSubmit = ({dispatch, commit}, { email, password }) => {
console.log(email, password)
commit(types.USER_LOGIN_REQUEST)
const options = {
url: `${API_URL}/token`
}
return request(options)
.then((response) => {
dispatch('getUserProfile')
commit(types.USER_LOGIN_SUCCESS, response.token)
return Promise.resolve(response.token)
})
.catch((error) => {
commit(types.USER_LOGIN_FAILURE, error)
return Promise.reject(error)
})
}
Run Code Online (Sandbox Code Playgroud)
Login.vue
handleFormSubmit () {
this.$store.dispatch('loginFormSubmit', formData)
.then(() => this.$router.push('/news'))
.catch(() => {
this.loginError = true
})
}
Run Code Online (Sandbox Code Playgroud)
然后在我的路由器中:
const routes = [
{
path: 'news',
alias: '',
component: NewsView,
name: 'News',
meta: { description: 'News feed page' },
beforeEnter: (to, from, next) => {
store.dispatch('getUserProfile')
- .then((resp) => {
- // Profile set
- next()
- })
- .catch(() => {
- // No profile set
- next({ name: 'settings' })
- })
}
},
]
Run Code Online (Sandbox Code Playgroud)
computed: {
isAuthenticated () {
return this.$store.getters.isAuthenticated
}
},
watch: {
isAuthenticated () {
this.$router.push('/calendar')
}
},
methods: {
handleSubmit (formData) {
// Updates isAuthenticated on success
this.$store.dispatch('requestAuthToken', formData)
}
}
Run Code Online (Sandbox Code Playgroud)
也许三号或四号最好?感觉最干净,但很想知道你们的想法:D
感谢您提前抽出时间!
我个人使用两种解决方案的组合来重定向/处理错误:
使用axios拦截器来获取最清晰的状态代码:
import axios from 'axios'
axios.interceptors.response.use(response => response, error => {
const { status } = error.response
const errorMessage = error.response.data.message
if (status === Constants.STATUS_CODE_ERROR_NOT_FOUND) {
router.push('/404')
return
} else if (status === Constants.STATUS_CODE_ERROR_UNAUTHENTICATED){
...
}
...
}
Run Code Online (Sandbox Code Playgroud)在组件中的action和return中进行检查,以进行重定向或其他必要的操作。
另一方面,请考虑使用async/await而不是then/catch.