vue3+ts 页面跳转传对象

问题描述:

进最近在使用vue3+ts+vite做了一个小项目,页面跳转需要传对象然而我就跟往常使用vue2和js的用法传参然后出现了问题

这里是页面a传参

 然后页面b进行接受参数的时候报错了

 原因可能是因为传参的类型跟接受参数的类型不符,因为使用ts所以对属性的类型有严格的规范所以解决方法如下

页面A跳转页面B

页面A:

//BlueContentDto是已经定义好接收数据的接口

const item:BlueContentDto =  {
        id: "1",
        name: "工作经验",
      }

const data = JSON.stringify(item)
router.push({
       path: '页面B路径',
       query: {
           conObj:encodeURIComponent(data )
       }
})

页面B:

interface RouteQuery extends LocationQuery {
  conObj: string;
}

const contentInfo = ref({} as BlueContentDto);
const routeQuery = route.query as RouteQuery;

if (route.query.conObj) {
  const str: string = decodeURIComponent(routeQuery.conObj);
  contentInfo.value = JSON.parse(str);
  console.log("接收参数", contentInfo.value);
}

声明一个RouteQuery接口并继承 LocationQuery 然后在声明一个接受类型就成功接收到传的对象

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Vue 3 + TypeScript 中,使用 Vue Router 进行路由跳转可以按照以下步骤进行: 1. 安装 Vue Router:使用 npm 或 yarn 安装 Vue Router ```bash npm install vue-router # 或者 yarn add vue-router ``` 2. 创建路由实例:在你的 `main.ts` 文件中,创建一个路由实例并将其挂载到 Vue 实例上。 ```typescript import { createApp } from 'vue' import { createRouter, createWebHistory } from 'vue-router' import App from './App.vue' import Home from './views/Home.vue' import About from './views/About.vue' const routes = [ { path: '/', component: Home }, { path: '/about', component: About } ] const router = createRouter({ history: createWebHistory(process.env.BASE_URL), routes }) createApp(App).use(router).mount('#app') ``` 3. 在组件中使用路由跳转:在你的组件中使用 `<router-link>` 标签来生成链接,并使用 `$router.push` 方法来导航到其他页面。 ```html <template> <div> <h1>Hello, World!</h1> <router-link to="/">Home</router-link> <router-link to="/about">About</router-link> <button @click="goToHome()">Go to Home</button> <button @click="goToAbout()">Go to About</button> </div> </template> <script lang="ts"> import { defineComponent } from 'vue' import { RouteLocationNormalized, Router } from 'vue-router' export default defineComponent({ methods: { goToHome() { this.$router.push('/') // or this.$router.push({ path: '/' }) }, goToAbout() { this.$router.push('/about') // or this.$router.push({ path: '/about' }) } }, // 如果需要在组件中使用路由对象,可以按照以下方式定义组件实例类型 // 以便在组件中访问路由对象的类型检查和自动补全 beforeRouteEnter(to: RouteLocationNormalized, from: RouteLocationNormalized, next: (to?: any) => void) { next((vm: any) => { vm.$router // 路由对象 vm.$route // 当前路由信息对象 }) } }) </script> ``` 这样就完成了在 Vue 3 + TypeScript 中使用 Vue Router 进行路由跳转的基本步骤。需要注意的是,在使用路由对象时,需要定义组件实例的类型,以便在组件中访问路由对象时进行类型检查和自动补全。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值