代码之家  ›  专栏  ›  技术社区  ›  Axel

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

  •  2
  • Axel  · 技术社区  · 6 年前

    我正在尝试验证页面组件中的路由参数,如下所示:

    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
        }
    }
    

    这根本不管用。即使我输入了无效的参数,它仍然会加载页面。请帮帮我!

    1 回复  |  直到 6 年前
        1
  •  3
  •   Nicolas Pennec    6 年前

    validate 方法必须返回布尔值:

    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)
    }