首页 > 解决方案 > Graphql的返回查询为空时如何在Nuxtjs中进行重定向

问题描述

我对 Nuxtjs 和 javascript 世界很陌生。我正在使用 Graphql 从后端(Strapi)获取所需数据的 Nuxtjs 项目。目标是在 Graphql 返回空查询结果时重定向到主页(index.vue)。但是,当我使用 router.push('/') 作为下面的代码时,它不起作用。

请注意,我正在尝试在结果块和挂载块上重定向。他们两个都没有工作。

请帮我指出我在这里做错了什么。提前感谢您的好意

<script>
import getProfiletQuery from '~/apollo/queries/profiles/profile'

export default {
  data () {
    return {
      profiles: {
      }
    }
  },
  apollo: {
    profiles: {
      prefetch: true,
      query: getProfiletQuery,
      variables () {
        return { user: this.$route.params.user }
      },
      result ({ data }) {
        if (data.profiles.length === 0) {
          console.log('it enters here!!!')
          this.$router.push('/') //this is not working
        }
      }
    }
  },
  mounted () {
    console.log('this.profiles.length: ', this.profiles.length)
    if (this.profiles.length === 0) {
      this.$router.push('/')
    }
  }
}
</script>

标签: javascriptgraphqlnuxt.jsapollo

解决方案


推荐阅读