如何验证 Nuxt 中的路由参数?

How to validate route parameter in Nuxt?

我正在尝试像这样在我的页面组件中验证路由参数:

async validate({ params, store }) {
    await store.dispatch(types.VALIDATE_PARAMS_ASYNC, params.id)
}

然后在店里:

async [types.VALIDATE_PARAMS_ASYNC]({state, commit, dispatch}, payload) {
    try {
        const res = await this.$axios.$post('/api/params/validate', {
            params: payload
        })
        commit(types.MUTATE_SET_INFO, res.data) // this mutation is in another module. This doesn't work either
        return true
    } catch(e) {
        return false
    }
}

这根本行不通。即使我输入无效参数,它仍会加载页面。请帮忙!

您的 validate 方法必须 return 布尔值:

async validate({ params, store}) {
    // await operations
   return true // if the params are valid
   return false // will stop Nuxt.js to render the route and display the error page
}

查看官方文档:https://nuxtjs.org/api/pages-validate#the-validate-method


async validate({ params, store }) {
    return await store.dispatch(types.VALIDATE_PARAMS_ASYNC, params.id)
}