如何以编程方式在组件内路由 - Vue Router

How to programmatically route inside a component - Vue Router

我有一个 Quasar 应用程序 运行 Vue 3 和 vue-router 4

我的路线已设置好,在使用

从组件模板导航时效果很好
<router-link to="/route">Go to route</router-link>

不过,我希望能够通过我的方法访问路由器和路由。根据文档,我应该能够以某种方式访问​​路由器对象,this.$router,或路由器,或其他方式......但我似乎无法访问

我的整个单文件组件看起来像

  <template>
    <q-page>
      <q-card>
        <q-form @submit="handleSubmit()" >
          <q-input v-model="param" />
          <q-btn label="submit" type="submit" />
        </q-form>
        <router-link to="/">Go to Foo</router-link> <!-- this works great -->
      </q-card>
    </q-page>
  </template>

  <script lang="ts">
  import { ref } from 'vue'

  export default {
    setup () {
      const param = ref(null);
      return { param }
    },
    methods: {
      async handleSubmit () {
         // do stuff
         // route somewhere
      }
    }
  }
  </script>

如何从 handleSubmit 方法访问 vue 路由器?

this.$routethis.$router 未定义,据我所知,vue 3 和 sfc 这种模式不适用。例如,对于我的商店,我需要使用 vuex mapStatemapActions

试试这个

<template>
    <q-page>
      <q-card>
        <q-form @submit="handleSubmit()" >
          <q-input v-model="param" />
          <q-btn label="submit" type="submit" />
        </q-form>
        <router-link to="/">Go to Foo</router-link> <!-- this works great -->
      </q-card>
    </q-page>
  </template>

  <script lang="ts">
  import { ref } from 'vue'

  export default {
    setup () {
      const param = ref(null);
      return { param }
    },
    methods: {
      async handleSubmit () {
         this.$router.push('/link/to/go/anywhere') <-- here
      }
    }
  }
  </script>

您是否忘记设置路由器视图 --> 标签,它应该在您的模板中的 App.vue 中,以便将您的组件数据呈现到您的路由器中,是的,使用它。$router.push ({ path: '你的路由器路径' }) 在你的方法中

选项 API 的类型推断需要 declaring components with the defineComponent() wrapper:

To let TypeScript properly infer types inside Vue component options, you need to define components with defineComponent global method:

import { defineComponent } from 'vue'

const Component = defineComponent({
  // type inference enabled
})

If you're using single-file components then this would typically be written as:

<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
  // type inference enabled
})
</script>

所以您的组件应该类似于:

<script lang="ts">
import { defineComponent } from 'vue'
                    
export default defineComponent({
  methods: {
    async handleSubmit () {
      // ✅
      this.$router.push('/')
    }
  }
})
</script>

或者,您可以使用 useRouter() in the Composition API:

<script lang="ts">
import { ref, defineComponent } from 'vue'
import { useRouter } from 'vue-router'

export default defineComponent({
  setup() {
    const router = useRouter()
    const handleSubmit = async () => {
      router.push('/')
    }

    return { handleSubmit }
  }
})
</script>