Vue3使用vue-router如何实现路由跳转与参数获取

 

vue-router实现路由跳转与参数获取

路由跳转和传参

import { defineComponent, onMounted, reactive, readonly, ref } from 'vue';
import { useRouter, useRoute } from 'vue-router';
export default defineComponent({
name: 'Login',
setup() {
  const router = useRouter(), route = useRoute();
  const submitForm = () => {
    formRef.value?.validate((valid) => {
      if (valid) {
        login({ strategy: 'local', ...ruleForm })
          .then((res: any) => {
          // 获取参数和路由跳转
            const redirect: string = route.query && route.query.redirect;
            if (redirect) {
              router.replace(redirect);
            } else {
              router.push('/home');
            }
            return true;
          })
          .catch((e) => {
            ...
          });
      } else {
       ...
        return false;
      }
    });
  };
  return { ..., submitForm };
}
});

 

路由跳转三种方法的总结

一、第一种

1、路由设置方式

{`在这里插入代码片`
  path: '/detail/:id',
  name: 'detail',
  meta: { keepAlive: true },
  component: () => import('../pages/detail/index')
}

2、路由跳转模式

this.$router.push(
  {
    path: `/detail/1`
  }
)

3、获取参数方式

let detailId = this.$route.params.id

注意: params 传参相当于是路由的一部分是必须传的东西,经过验证不传页面会跳转到空白页

该方式刷新页面id 不丢失

二、第二种

1、路由设置方式

{
  path: '/detail/:id',
  name: 'detail',
  meta: { keepAlive: true },
  component: () => import('../pages/detail/index')
}

2、路由跳转模式

this.$router.push(
  {
    name: 'Detail',
    params: {
      id
    }
  }
)

3、获取参数方式

let detailId = this.$route.params.id

注意:此方式传参 路由设置方式中的 id 可以传也可以不传,不传刷新页面id 会丢失

该方式刷新页面id 不丢失

三、第三种

1、路由设置方式

{
  path: '/detail',
  name: 'detail',
  meta: { keepAlive: true },
  component: () => import('../pages/detail/index')
}

2、路由跳转模式

this.$router.push(
  {
    path: 'Detail',
    query: {
      id
    }
  }
)

3、获取参数方式

let detailId = this.$route.query.id

注意:此方式传参 路由设置方式中的 id 不能写,因为写了就是router 的一部分,这样就会匹配不到, 此方式刷新页面id 不丢失

http://localhost:8080/#/detail?id=1

总结: params一旦设置在路由,params就是路由的一部分,如果这个路由有params传参,但是在跳转的时候没有传这个参数,会导致跳转失败或者页面会没有内容。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程宝库

 Vue+ts里this.$store问题vuex里面我调用this.$store访问仓库state时,调用失败报错解决办法(this as any).$store  Vu ...