Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use router in vue composition api?

I defined a route in vue:

/users/:userId

Which point to UserComponent:

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

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

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?

here is my code:

<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>
like image 385
Jon Sud Avatar asked Mar 19 '20 10:03

Jon Sud


People also ask

How do I push my Vue router?

Note: Inside of a Vue instance, you have access to the router instance as $router . You can therefore call this.$router.push . To navigate to a different URL, use router.push . This method pushes a new entry into the history stack, so when the user clicks the browser back button they will be taken to the previous URL.

Can I use Vue router with CDN?

You can directly download the latest version of vue-router from CDN. It is available at https://unpkg.com/vue-router/dist/vue-router.js. The unpkg.com contains the npm-based cdn links and always updated to the recent version.

What is Vue router in Vuejs?

Vue Router is the official router for Vue. js. It deeply integrates with Vue. js core to make building Single Page Applications with Vue.


2 Answers

as with documentation from vue-router site

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,
        },
      })
    }
    }
  },
}
like image 178
ndotie Avatar answered Sep 19 '22 14:09

ndotie


A had the same problem. I use vue 2 and @vue/composition-api

My resolution:

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

after that, I can usage:

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

Resolution for you:

// replace:
// const userToLoad = computed(() => root.$route.params.userId);
// to:  
import { useRoute } from '@/router/migrateRouterVue3';
//...
const route = useRoute();
const userToLoad = computed(() => route.params.userId);
like image 24
Андрей Сорока Avatar answered Sep 20 '22 14:09

Андрей Сорока