【问题标题】:Process 404 page when there is no parameter in VueVue中无参数时处理404页面
【发布时间】:2021-12-03 08:32:17
【问题描述】:

正在使用动态路由。

如果vuex中没有设备数据,我想去404页面。

我应该如何实现它?

路由器/index.js

const routes = [
  {
    path: '/',
    name: 'Main',
    component: Main
  },
  {
    path: '/:device',
    name: 'Detail',
    component: Detail,
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: NotFound
  },

]

设备详情页如下实现时,不会移动到404页面。

    const deviceName = route.params.device
    const storedDeviceList = computed(() => store.state.stationName)

    if (!storedDeviceList.value.includes(deviceName)) {
      router.push({
        name: 'NotFound'
      })
    }

【问题讨论】:

  • 你能提供你在商店里是如何处理这个问题的吗?
  • Vuex-store 有一个包含设备列表的 stationName。 store/index.js => state: { stationName: [ 'sample', ], }
  • 所以,如果stationName没有参数(router-parameter),我尝试移动到NotFound页面。
  • 你能提供deviceNamestoredDeviceList的例子吗?因为我不明白,为什么这不起作用。
  • 抱歉检查晚了。我在 github 上发布了一个代码示例。 (github.com/airwalk741/router-test) 状态下只有 test_device。如果您转到 test_device 以外的 URL,则会收到错误消息。 (例如localhost:8081/test123这个地方会抛出错误。)

标签: vue.js vue-router vuejs3


【解决方案1】:

我认为第一个问题是,根据您的 github 存储库,您在项目中声明了两次 router。您在 router/index.js 中声明了您的路线并将其导入您的 main.js。因此,从vue-router 而不是router.js 再次将其导入About.vue 会导致此实例没有路由。第二个问题与您的商店相同,因为您将store/index.js 导入您的main.js,但将一个新实例从vuex 导入您的About.vue

如果您要使用组合 API,您可以使用 this 调用已经在 main.js 中导入的模块,例如:

this.$router.push({
   name: 'NotFound'
})

您还可以像这样从您的商店获取您的状态:

this.$store.state.stationName

因此,在组合 API 中,在您的 About.vue 中使用类似这样的内容:

<script>
export default {
  methods: {
    checkDevice() {
      if (!this.$store.state.deviceList.includes(this.$route.params.device)) {
        this.$router.push({
          name: 'NotFound'
        })
      }
    }
  },
  created() {
    this.checkDevice()
  }
}
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-19
    • 2019-08-08
    • 2019-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-08
    相关资源
    最近更新 更多