vue.js - Vue Router - 使用 Vue 2 Composition API 获取路由参数

标签 vue.js vuejs2 vue-router vuejs3 vue-composition-api

我正在使用 Vue 2 Composition API并希望从我的 setup() 中的 Vue Router 访问路由参数方法。
Vue Router documentation 中所述:

Because we don't have access to this inside of setup, we cannot directly access this.$router or this.$route anymore. Instead we use the useRouter function:

import { useRouter, useRoute } from 'vue-router'

export default {
  setup() {
    const router = useRouter()
    const route = useRoute()

    function pushWithQuery(query) {
      router.push({
        name: 'search',
        query: {
          ...route.query,
        },
      })
    }
  },
}

不幸的是,这个方法在 Vue 2 的 Vue Router 中不可用。我在这里有什么选择,我如何使用 Vue 2 Composition API 访问我的路由参数?

最佳答案

在 vue 2 组合 API 中,您拥有 root设置上下文中引用根组件的属性,尝试使用它而不是 this :

export default {
  setup(props,context) {
    const router = context.root.$router;
    const route = context.root.$route;

    function pushWithQuery(query) {
      router.push({
        name: 'search',
        query: {
          ...route.query,
        },
      })
    }
  },
}

关于vue.js - Vue Router - 使用 Vue 2 Composition API 获取路由参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66815981/

相关文章:

javascript - Vuetify 按行单选数据表

vue.js - 服务器端渲染 Vue 与 ASP.NET Core 2

authentication - 我想在 Nuxt.js 的 Vuex 中使用 window.localStorage

javascript - Vue在两个组件之间切换的过渡动画不流畅

vue.js - 我应该还是不应该在vue3中安装body元素?

vue.js - Vuex 4 + Vue 3 在模块中使用共享状态操作

javascript - 渲染 vue.js 组件并传入数据

vue.js - 嵌套路由打破了静态路径

javascript - 定义 Vue-Router 路由时访问 Vuex 状态

javascript - Vue路由器: fetching data from server (asynchronously with ajax) does not update the view in component