Vue-路由配置、路由跳转及传参

路由配置

在src下新建已经router文件夹,里面放置路由配置文件

  • src\router\index.ts

引入相关插件:

import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'

根据项目需要引入组件并配置路由,写在第一个的路由为默认路由。

import 组件名 from '组件位置'

const routes: Array<RouteRecordRaw> = [
  {
    path: '路由路径',
    name: '路由名',
    component:组件名,
    meta: {
      title: ''
    },

    .......
  },

创建及暴露路由:

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

export default router

示例: 

import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import Index from '../views/index/index.vue'
import Merchant from '../views/merchant/index.vue'
import Hotel from '../views/hotel/index.vue'
import Ticket from '../views/ticket/index.vue'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/index',
    name: 'index',
    component: Index,
    meta: {
      title: ''
    }
  },
  {
    path: '/merchant',
    name: 'merchant',
    component: Merchant,
    meta: {
      title: '商家'
    }
  },
  {
    path: '/hotel',
    name: 'hotel',
    component: Hotel,
    meta: {
      title: '酒店'
    }
  },
  {
    path: '/ticket',
    name: 'ticket',
    component: Ticket,
    meta: {
      title: '门票'
    }
  },
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

export default router

页面跳转方式

需要跳转路由的文件需先引入:

import router from "@/router/index";

router对象:useRouter获取

import { useRouter } from 'vue-router'
const router = useRouter()
const btn = function () {
  console.log(router)
  router.push({
    path: "",
    query: {
    },
  });
}

 router对象中包含了多个方法,让我们去操作我们的路由,比如:addRoute动态添加路由,push跳转页面等

route对象:userRoute获取

import { useRoute } from 'vue-router'
const route = useRoute()
const btn = function () {
  console.log(route)
  route.push({
    path: "",
    query: {
    },
  });
}

 fullPath、path是路径,query、params是传参方式,我们想要获取路径的内容都可以通过route对象来获取

使用router-link进行跳转

写法一:<router-link to="/about">点击</router-link>
写法二:<router-link :to="{path: '/about'}">点击</router-link>
写法三:<router-link :to="{name: 'about'}" >点击</router-link>:注,如果路由中未配置name,那么使用name则会报错

传参方式

query和params

 query:参数在url地址上以问号的形式在其后面拼接,query传参对应path去跳转页面

 params:参数在路由对象中拼接,如果不进行拼接,第一次页面跳转过来我们可以获取到传递过来的参数,回车刷新后则参数丢失

接收参数

从vue-router中引入useRoute方法,定义变量使其等于这个函数的返回值,返回值是个对象,其中存在query和params参数,可以直接拿来使用

import { useRouter } from "vue-router";

query:传递过来的参数直接使用query.参数名称去接,

被跳转至的组件需引入方法,创建路由对象和接收参数:

示例:

    // 路由对象
    const router = useRouter();
    //接收参数
    const orderItemId = router.currentRoute.value.query.orderItemId || "";
    const orderType = router.currentRoute.value.query.orderType || 0;

params:传递过来的参数直接使用params.参数名称去接

const route = useRoute()
console.log(route.params.id)
const state = route.params

猜你喜欢

转载自blog.csdn.net/m0_53206841/article/details/125409653