如何在Vue Composition API中使用路由器?

时间:2020-03-19 10:52:03

标签: vue.js

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

/users/:userId

指向UserComponent的地方

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

,我使用computed中的@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>

6 个答案:

答案 0 :(得分:1)

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

这是路由配置的样子:

      {
        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()将在定义和反应性依赖项时立即运行。更改

答案 1 :(得分:1)

您可以这样做:

import { useRoute } from 'vue-router';

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

答案 2 :(得分:0)

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

答案 3 :(得分: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

答案 4 :(得分:0)

与来自 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,
        },
      })
    }
    }
  },
}

答案 5 :(得分:-1)

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