12

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

/users/:userId

哪个指向 UserComponent:

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

我使用computedfrom@vue/composition-api来获取数据。

问题是当路由更改为另一个时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>
4

7 回答 7

7

你可以这样做:

import { useRoute } from 'vue-router';

export default {
  setup() {
    const route = useRoute();
    // Now you can access params like:
    console.log(route.params.id);
  }
};
于 2020-11-17T15:34:53.337 回答
4

您可以将参数作为道具传递给您的组件。默认情况下,道具是反应式的。

这是路由配置的样子:

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

然后,您可以使用组件中的道具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()将在定义时和响应式依赖项时立即运行。change

于 2020-09-10T11:08:22.777 回答
4

A也有同样的问题。我使用 vue 2 和 @vue/composition-api

我的决议:

创建:src/router/migrateRouterVue3.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);
于 2021-03-16T20:39:35.677 回答
3

与来自 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,
        },
      })
    }
    }
  },
}
于 2021-07-29T22:38:42.390 回答
0

以下useRoute钩子将使route反应变得可行,因此它是可行的:

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;
};

于 2021-12-23T18:28:48.007 回答
0
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

于 2021-06-15T09:06:06.220 回答
-2

请添加此代码:watchEffect(() => userToLoad);

于 2020-08-09T23:32:38.733 回答