如何在vue合成API中使用路由器?

rqcrx0a6  于 2023-01-14  发布在  Vue.js
关注(0)|答案(8)|浏览(236)

我在vue中定义了一条路由:

/users/:userId

哪个指向UserComponent:

<template>
 <div>{{username}}</div>
</template>

我使用@vue/composition-api中的computed来获取数据。
问题是当路线改变到另一个userId,通过导航到另一个用户,在html模板中的用户没有改变,因为我所期望的.它也不做重定向时,用户不在列表中.
我能做些什么来弥补呢?
下面是我代码:

<template>
  <div>{{username}}</div>
</template>

<script lang="ts">
import { computed, defineComponent, ref, getCurrentInstance } from '@vue/composition-api';

export const useUsername = ({ user }) => {
  return { username: user.name };
};

export default defineComponent({
  setup(props, { root }) {
    const vm = getCurrentInstance();

    const userToLoad = computed(() => root.$route.params.userId);
    const listOfUsers = [
      { userId: 1, name: 'user1' },
      { userId: 2, name: 'user2' },
    ];

    const user = listOfUsers.find((u) => u.userId === +userToLoad.value);
    if (!user) {
      return root.$router.push('/404');
    }

    const { username } = useUsername({ user });

    return { username };
  },
});

</script>
polkgigr

polkgigr1#

你可以这样做:

import { useRoute } from 'vue-router';

export default {
  setup() {
    const route = useRoute();
    // Now you can access params like:
    console.log(route.params.id);
  }
};
nwo49xxi

nwo49xxi2#

vue-router文档中:

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

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

        function pushWithQuery(query) {
            if (!user) {
                router.push({
                    name: '404',
                    query: {
                        ...route.query
                    }
                })
            }
        }
    }
}
wf82jlnq

wf82jlnq3#

你可以把参数作为 prop 传递给你的组件。 prop 默认是被动的。
路由配置可能如下所示:

{
        path: '/users/:userId',
        name: Users,
        component: YourComponent
      },

然后,可以将组件中的props与watchEffect()一起使用

<template>
  <div>{{username}}</div>
</template>

<script lang="ts">
import { computed, defineComponent, ref, getCurrentInstance, watchEffect } from '@vue/composition-api';

export const useUsername = ({ user }) => {
  return { username: user.name };
};

export default defineComponent({
  props: {userId: {type: String, required: true },
  setup(props, { root }) {
    const vm = getCurrentInstance();
    const user = ref()

    const userToLoad = computed(() => props.userId);
    const listOfUsers = [
      { userId: 1, name: 'user1' },
      { userId: 2, name: 'user2' },
    ];

    watchEffect(() => user.value = listOfUsers.find((u) => u.userId === +userToLoad.value))
    
    if (!user) {
      return root.$router.push('/404');
    }

    const { username } = useUsername({ user });

    return { username };
  },
});

</script>

watchEffect()将在定义和React性依赖项时立即运行。更改

dojqjjoe

dojqjjoe4#

A也有同样的问题,我使用vue 2和@vue/composition-api
我的决心:
创建日期:src/路由器/迁移路由器Vue3.js

import { reactive } from '@vue/composition-api';
import router from './index';

const currentRoute = reactive({
  ...router.currentRoute,
});

router.beforeEach((to, from, next) => {
  Object.keys(to).forEach(key => {
    currentRoute[key] = to[key];
  });
  next();
});

// eslint-disable-next-line import/prefer-default-export
export function useRoute() {
  return currentRoute;
}

之后,我可以使用:

// import { useRoute } from 'vue-router';
import { useRoute } from '@/router/migrateRouterVue3';

您的解决方案:

// replace:
// const userToLoad = computed(() => root.$route.params.userId);
// to:  
import { useRoute } from '@/router/migrateRouterVue3';
//...
const route = useRoute();
const userToLoad = computed(() => route.params.userId);
xfyts7mz

xfyts7mz5#

function useRoute() {
  const vm = getCurrentInstance()
  if (!vm) throw new Error('must be called in setup')

  return vm.proxy.$route
}

https://github.com/vuejs/composition-api/issues/630

gcuhipw9

gcuhipw96#

下面的useRoute钩子将使route成为React式的,因此它是可行的:

const route = useRoute();
const fooId = computed(()=>route.params.fooId);
let currentRoute = null;
export const useRoute = () => {
  const self = getCurrentInstance(); 
  const router = self.proxy.$router;
  if (!currentRoute) {
    const route = { ...self.proxy.$route };
    const routeRef = shallowRef(route);
    const computedRoute = {};
    for (const key of Object.keys(routeRef.value)) {
      computedRoute[key] = computed(() => routeRef.value[key]);
    }
    router.afterEach((to) => {
      routeRef.value = to;
    });
    currentRoute = reactive(computedRoute);
  }
  return currentRoute;
};
2eafrhcq

2eafrhcq7#

vue2-helpers包提供了一个useRoute函数,您可以在Vue 2.7(以及2.6、2.5)中使用。
安装

# Vue 2.7
$ npm install vue2-helpers@2
# Vue 2.5 and 2.6
$ npm install vue2-helpers@1

用法

import { useRoute } from 'vue2-helpers/vue-router';

const route = useRoute();
const id: string | undefined = route.params.id;
lnxxn5zx

lnxxn5zx8#

请添加此代码:watchEffect(()=〉用户加载);

相关问题