安装一个VSCode插件,JSON to TS,然后选中JSON,同时按Ctrl+Shift+Alt+S,就能快速的生成数据类型
比如:
[
{
shopId:10001,
shopName:"精品男装秋季外套",
shopPrice:180
},{
shopId:10002,
shopName:"男装时尚牛仔裤",
shopPrice:220
},{
shopId:10003,
shopName:"白色休闲运动鞋",
shopPrice:170
}
]
通过这个插件最终可以生成:
interface RootObject {
shopId: number;
shopName: string;
shopPrice: number;
}
根据个人的习惯,可以把interface改成type的写法即可
1.通过query方式传参:
index.vue:
<template>
<div>
<table border="1" width="600">
<tr>
<th>商品名称</th>
<th>商品价格</th>
<th>操作</th>
</tr>
<tr v-for="(item,index) in shopData" :key="index">
<td align="center">{{item.shopName}}</td>
<td align="center">¥{{item.shopPrice}}</td>
<td align="center">
<button @click="handleDetail(item)">查看详情</button>
</td>
</tr>
</table>
</div>
</template>
<script setup lang='ts'>
import { reactive } from 'vue';
import { useRouter } from 'vue-router'
const router = useRouter()
type Shop = {
shopId:number,
shopName:string,
shopPrice:number
}
const shopData = reactive<Shop[]>([
{
shopId:10001,
shopName:"精品男装秋季外套",
shopPrice:180
},{
shopId:10002,
shopName:"男装时尚牛仔裤",
shopPrice:220
},{
shopId:10003,
shopName:"白色休闲运动鞋",
shopPrice:170
}
])
const handleDetail = (data:Shop) => {
console.log(data)
// router.push({path:'/index',query:{id:data.shopId}})
router.push({path:'/index',query:data})
}
</script>
detail.vue:
<template>
<div>
商品名称: {{route.query?.shopName}} - 商品价格: ¥{{route.query?.shopPrice}}
</div>
</template>
<script setup lang='ts'>
import { useRoute } from 'vue-router'
const route = useRoute()
</script>
* 用router传参就用route去接收,同样也需要在vue-router去声明useRoute方法
2.通过params方式传参:
只需要把path改成name,并且把query改成params即可,在接收页面用params去接
比如:router.push({ name: 'index', params: { name: "aaa" } })
query 和 params 传参的区别:
- 1.query传参配置的是path,params传参配置的是name,在params中配置path无效
- 2.query在路由配置不需要设置参数,而params必须设置
- 3.query传递的参数会显示在地址栏中
- 4.parqams传参刷新会无效,而query刷新不变
- 5.路由配置