如何在 vue 组合 api 中使用路由器? [英] How to use router in vue composition api?

查看:55
本文介绍了如何在 vue 组合 api 中使用路由器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I defined a route in vue:

/users/:userId

指向 UserComponent:

Which point to UserComponent:

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

我使用 @vue/composition-api 中的 computed 来获取数据.

and I use computed from @vue/composition-api to get the data.

问题是当路由更改为另一个 userId 时,通过导航到另一个用户,html 模板中的用户没有按照我的预期进行更改.当用户不在列表中时,它也不会重定向.

the problem is when the route change to another userId, by navigate to another user, the user in the html template not changed as what I expected. also it doesn't do redirect when the the user is not in the list.

那么我能做些什么来解决这个问题?

So what I can do to fix that?

这是我的代码:

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

推荐答案

你可以这样做:

import { useRoute } from 'vue-router';

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

这篇关于如何在 vue 组合 api 中使用路由器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆